Java 为什么提前设置多个单亲会导致刷新失败?
我正在创建一个JPA实体,与多通建立关系。为什么有Java 为什么提前设置多个单亲会导致刷新失败?,java,jpa,openjpa,Java,Jpa,Openjpa,我正在创建一个JPA实体,与多通建立关系。为什么有child.setParent(parent)导致在刷新()过程中出现以下故障: 失败的测试代码: Parent parent = new Parent(); Child child = new Child(); ChildPrimaryKey childPrimaryKey = new ChildPrimaryKey(); childPrimaryKey.setLookupId(1); child.set
child.setParent(parent)代码>导致在刷新()过程中出现以下故障:
失败的测试代码:
Parent parent = new Parent();
Child child = new Child();
ChildPrimaryKey childPrimaryKey = new ChildPrimaryKey();
childPrimaryKey.setLookupId(1);
child.setId(childPrimaryKey);
child.setParent(parent); // <-- FAIL because of this
// Begin transaction
entityManager.clear();
entityManager.getTransaction().begin();
LOGGER.info("Persisting parent without child.");
entityManager.persist(parent);
LOGGER.info("Updating parent with child.");
childPrimaryKey.setParentId(parent.getId());
parent.getChildren().add(child);
entityManager.merge(parent);
// Fail happens at flush
entityManager.flush();
Parent=newparent();
子项=新子项();
ChildPrimaryKey ChildPrimaryKey=新的ChildPrimaryKey();
setLookupId(1);
setId(childPrimaryKey);
child.setParent(parent);// 我相信你的MapsId
应该是@MapsId(“parentId”)
基于你所展示的类结构。MapsId
的值是一个属性,而不是列名
Parent parent = new Parent();
Child child = new Child();
ChildPrimaryKey childPrimaryKey = new ChildPrimaryKey();
childPrimaryKey.setLookupId(1);
child.setId(childPrimaryKey);
child.setParent(parent); // <-- FAIL because of this
// Begin transaction
entityManager.clear();
entityManager.getTransaction().begin();
LOGGER.info("Persisting parent without child.");
entityManager.persist(parent);
LOGGER.info("Updating parent with child.");
childPrimaryKey.setParentId(parent.getId());
parent.getChildren().add(child);
entityManager.merge(parent);
// Fail happens at flush
entityManager.flush();
@Embeddable
public class ChildPrimaryKey {
@Column(name = "lookup_id")
private int lookupId;
@Column(name = "parent_id")
private long parentId;
}
@Entity
@Table(name = "child")
public class Child {
@EmbeddedId
private ChildPrimaryKey id;
@MapsId("parent_id")
@ManyToOne
private Parent parent;
}
@Entity
@Table(name = "parent")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Child> children;
}