Hibernate保存新的一对一实体映射

时间:2014-06-24 09:05:23

标签: java spring hibernate java-ee

我试图在数据库上保留两个新实体并在它们之间进行映射时遇到问题

父实体:

@OneToOne(cascade = CascadeType.MERGE, mappedBy = "conflictOfInterest") 
@XmlTransient
@JsonIgnore
@Getter 
@Setter 
private RequestForCorrection requestForCorrection;

子实体:

@OneToOne()
@JoinColumn(name = "conflict_of_interest_id")
@JsonIgnore
@XmlTransient
@Getter
@Setter
private ConflictOfInterest conflictOfInterest;

当RequestForCorrection和ConflictOfInterest为ID null且我有

requestForCorrection.setConflictOfInterest(conflictOfInterest)
save(requestForCorrection)

Hibernate抛出异常

Caused by: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing: com.greenvalley.etendering.domain.RequestForCorrection.conflictOfInterest -> com.greenvalley.etendering.domain.ConflictOfInterest
at org.hibernate.engine.spi.CascadingAction$8.noCascade(CascadingAction.java:380) ~[hibernate-core-4.2.7.Final.jar:4.2.7.Final]

我尝试将父级的级联注释更改为ALL和PERSIST而没有任何成功。 我希望节省级联,所以

save(conflictOfInterest)
requestForCorrection.setConflictOfInterest(conflictOfInterest)
save(requestForCorrection)  

我不认为有效的解决方案

1 个答案:

答案 0 :(得分:1)

保存父表休眠时,它正在尝试创建具有对父表的新引用的Child表。我建议你改变2个。

首先,如果您希望父级中的所有更改都转到子级,则将CascadeType从Merge更改为ALL

其次,将nullable = false添加到Child以强制在插入中添加fk。

@OneToOne(cascade = CascadeType.ALL, mappedBy = "conflictOfInterest")
@XmlTransient
@JsonIgnore
@Getter
@Setter
private RequestForCorrection requestForCorrection;      

@OneToOne
@JoinColumn(name = "conflict_of_interest_id", nullable = false)
@JsonIgnore
@Getter
@Setter
private ConflictOfInterest conflictOfInterest;