我有两个实体:
主
@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "seq")
private Integer seq;
@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "seq", referencedColumnName = "seq")
private SubMaster subMaster;
...................
}
Sub Master:
@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {
@Id
@Column(name = "seq")
private Integer seq;
private String subName;
...................
}
当我试图通过设置Master
实体来持久化SubMaster
实体时,我会遇到以下异常:
javax.persistence.PersistenceException: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned beforeQuery calling save(): SubMaster
然而,我期待Hibernate会在父实体被持久化时自动持久保存子实体。
答案 0 :(得分:2)
为SubMaster添加@GeneratedValue(strategy = IDENTITY),看起来像SubMaster的id生成了异常
答案 1 :(得分:2)
首先,你颠倒了协会的所有者,因为我认为subMaster应该有@JoinColumn注释。
现在解决方案
取决于JPA版本:
-2.0您可以在关系注释上定义@Id
注释,这样您就可以使用
@Entity
@Table(name = "master")
public class Master implements java.io.Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "seq")
private Integer seq;
@OneToOne(mappedBy = "master", cascade = CascadeType.ALL)
private SubMaster subMaster;
}
@Entity
@Table(name = "sub_master")
public class SubMaster implements java.io.Serializable {
@Id
@JoinColumn(name = "seq", referencedColumnName = "seq")
@OneToOne
private Master master;
private String subName;
}
你告诉你的孩子实体取父母的身份
master.setSubMaster(subMaster);
subMaster.setMaster(master)
-1.0你几乎被卡住,因为你被迫将@Id
放在一个基本的注释上,所以你需要将一个id和一个关系列分开,问题是@GeneratedValue
你是强制首先保存父项,然后在保存