【问题标题】:Hibernate save new one to one entities mappingHibernate 保存新的一对一实体映射
【发布时间】:2014-06-24 09:05:22
【问题描述】:

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

父实体:

@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)  

我不认为一个有效的解决方案

【问题讨论】:

  • 我认为连接列注释可以放在requestForCorrection字段上。
  • 这可能取决于save 操作的真正作用。您可以将其添加到问题中吗?
  • @Tony 如果我们更改 ForeignKey 我们有 SQL 外键异常。
  • @awb 就像我描述的那样,保存必须在级联上坚持父母和孩子,你还需要知道什么?
  • 它的内部表示可能会有所帮助。否则为什么不直接打电话给entityManager.persist()

标签: java spring hibernate jakarta-ee


【解决方案1】:

当保存父表休眠时,它试图创建对父表有新引用的子表。我建议您进行 2 次更改。

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

其次,给Child加上nullable = false,强制fk在insert中加入。

@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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 2012-04-21
    相关资源
    最近更新 更多