Hibernate 当表没有主键时,@Entity中的@Id只在一个事务中工作,而不是在多个事务中工作?

Hibernate 当表没有主键时,@Entity中的@Id只在一个事务中工作,而不是在多个事务中工作?,hibernate,jpa,Hibernate,Jpa,我想知道,要使@Id注释正常工作,数据库中的表是否需要主键。(对于@ManyToOne注释和外键也是如此,但我还没有研究过这种情况) 数据库中有一个表foo,它没有主键,只有两列id和name 在Java中有一个@实体Foo,它有两个属性:@Id和字符串名 在persistence.xmlhibernate.hbm2ddl.auto中,不是create;桌子已经在那儿了 在同一事务中使用相同的id保存2Foos时,Hibrate抗议:javax.persistence.EntityExistsE

我想知道,要使
@Id
注释正常工作,数据库中的表是否需要主键。(对于
@ManyToOne
注释和外键也是如此,但我还没有研究过这种情况)

数据库中有一个表
foo
,它没有主键,只有两列
id
name

在Java中有一个
@实体Foo
,它有两个属性:
@Id
字符串名

在persistence.xml
hibernate.hbm2ddl.auto
中,不是
create
;桌子已经在那儿了

在同一事务中使用相同的
id
保存2
Foo
s时,Hibrate抗议:javax.persistence.EntityExistsException:具有相同标识符值的不同对象已与会话关联

那么Hibernate真的接管了数据库中主键的功能吗 (索引除外)

但是当我将两个
Foo
分别保存在两个事务中时,它们会保存到数据库中,因此Hibrate的
@Id
不能作为主键

@Id
仅在同一事务中有效,这是故意的吗

Java中的实体和事务是:

@Entity
public class Foo {

    @Id
    private Long id;

    private String name;

    // <init>s and getters and setters


public class EntityTests

    private String name;
    @Test
    public void test2() throws Exception {
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        Foo foo=new Foo(1l,"bar");
        entityManager.persist(foo);

        entityManager.getTransaction().commit();
        entityManager.close();

        entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();

        Foo foo2=new Foo(1l,"baz");
        entityManager.persist(foo2);

        entityManager.getTransaction().commit();
        entityManager.close();
    }

如果您阅读hibernate中标识符的文档,它会说它们假定相应的db列是唯一的、不是空的和不可变的,因此当您已经有数据库表时,您需要确保表中相应的标识符列符合这些要求

sql> select*from foo;
ID | NAME
1  | bar
1  | baz