Spring Boot 專案中有一些代碼(為簡潔起見):
@Transactional
public void serviceMethod() {
var child = Child.builder().value(...).build();
var parent = parentEntityRepository.findById(5);
child.setParent(parent);
parent.getChildren().clear();
parent.getChildren().add(child);
}
@Entity
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL,orphanRemoval = true)
@Fetch(FetchMode.SUBSELECT)
private List<Child> children = new ArrayList<>();
}
@Entity
public class Child {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JoinColumn(name = "parent_id")
private Parent parent;
// this field has UNIQUE constaint in the project's Postgres DB
private String value;
}
并且child_table在其列之一上具有唯一索引。我不明白,為什么它不起作用,因為“獨特的約束違反錯誤”而失敗。正如我在這里所讀到的,Hibernate 重繪 順序以OrphanRemovalAction 開頭,因此上面的代碼似乎是正確的,但是在使用生成的本機 SQL 檢查 Hibernate 日志時,在事務提交后沒有發出任何 DELETE 陳述句。
uj5u.com熱心網友回復:
有一個已知的 Hibernate 錯誤描述了這個問題。
目前,級聯在(ophan-removal)INSERT之前執行新物體的。DELETE
要解決此問題,您可以在清除串列后重繪 會話一次。這樣,在將持久性級聯到新關聯的子級(觸發其插入)之前完成孤兒洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411352.html
標籤:
