我定义了以下实体:
@Entity
public class Child implements Serializable
{
@Id
@ManyToOne(cascade = CascadeType.ALL)
public Parent parent;
@Id
public int id;
}
@Entity
public class Parent
{
@Id
public int id;
}
当我尝试使用以下代码保留一个 Child 时:
Parent p = new Parent();
p.id = 1;
Child c1 = new Child();
c1.id = 1;
c1.parent = p;
em.persist(c1);
Hibernate 抛出“引用完整性约束冲突”错误:
Caused by: org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK3E104FC802AAC0A: PUBLIC.CHILD FOREIGN KEY(PARENT_ID) REFERENCES PUBLIC.PARENT(ID) (1)"; SQL statement:
insert into Child (parent_id, id) values (?, ?) [23506-171]
我相信这是因为它先插入子对象,然后再插入父对象,而我希望它先插入父对象。知道如何更改插入顺序,或者如何以其他方式解决这个问题吗?
更新:请注意,此方法不符合 JPA,但使用了 Hibernate 特性(请参阅 hibernate docs 中的 5.1.2.1. 复合标识符 部分)
更新:我只想保留 Child c1 并自动将持久级联到 Parent p(此更新是对下面@Alf 的回答的 react )。
最佳答案
em.persist(p);
em.persist(c1);
更新
我认为问题在于您的代码不符合 JPA。尝试使用 embeddedId,它对我有用。
@Embeddable
public class ChildPK implements Serializable {
private int parentId;
private int childId;
// getters and setters
}
@Entity
public class Child implements Serializable {
@EmbeddedId
public ChildPK id = new ChildPK();
@MapsId( "parentId" )
@ManyToOne
public Parent parent;
}
Parent p = new Parent();
p.id = 1;
Child c1 = new Child();
c1.id.setChildId( 1 );
c1.parent = p;
em.persist( c1 );
我认为它也适用于 @IdClass
,但我从未使用过它。
关于jpa - 在 JPA 中,将多对一作为主键会引发引用完整性约束冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17592247/