處理這種情況的正確方法是什么:
我有一個包含 4 個步驟的流程,每個步驟都映射到其物體類并連接到一個父物體(ParentEntity 以一對一的關系連接到每個 StepNEntity)。進行下一步時,當前步驟將保存到 DB。
@Entity
public class ParentEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@OneToOne(mappedBy = "parentEntity")
private Step1 step1;
@OneToOne(mappedBy = "parentEntity")
private Step2 step2;
...
}
@Entity
public class Step1 {
@MapsId
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private ParentEntity parentEntity;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
...
}
@Entity
public class Step2 {
@MapsId
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private ParentEntity parentEntity;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
...
}
我將使用 Step1 的 ParentEntity 保存到使用repository.save(). 在我嘗試的第二步
parentEntity.setStep2(step2); // step2 is a model in my flow view
parentRepository.save(parentEntity); // produces org.hibernate.PersistentObjectException: detached entity passed to persist:
同樣,如果我嘗試,我會得到例外
step2.setParentEntity(parentEntity);
step2Repository.save(step2);
uj5u.com熱心網友回復:
我的問題出在@MapsId我錯誤添加的注釋中。手動設定ParentEntity和洗掉所述注釋后,我的代碼有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/446111.html
上一篇:無法使用SpringBoot和JPA在資料庫中創建表
下一篇:很難理解Scala的基礎知識
