我有以下实体:
@Entity
@Table(name = "parent")
public class Parent {
@Id
private String id;
@OneToOne(mappedBy = "parent")
private Child child;
//getters, setters...
}
@Entity
@Table(name = "child")
public class Child {
public Child() {
}
public Child(Parent parent) {
this.parent = parent
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private String id;
@MapsId
@OneToOne
private Parent parent;
//getters, setters...
}
问题如下。我用来更新这些实体的过程通常如下。首先我做
Parent p = new Parent();
p.setId("parentId1");
em.persist(p);
因此,在这种情况下,Child
权利为null
稍后我可能想要添加一个子实体,所以我做了类似以下的事情:
Parent parent = em.findById(parent.getId());
Child child = new Child(parent);
em.persist(child);
现在我假设由于Parent有@MapsId注释,它通常应该通过复制Parent Id来生成Child的id,并且实体应该被保留。但是,我收到以下约束违例异常。
SqlExceptionHelper: Duplicate entry 'parentId1' for key 'PRIMARY'
org.hibernate.exception.ConstraintViolationException: could not execute statement;