我正在使用Spring Data和休眠,CascadeType.ALL
和orphanRemoval = true
。休眠刪除非孤兒
問題是,當將子實體從parentX移動到parentY時,如果parentY在parentX之前持久化,則Hibernate將從子數據庫中刪除子實體。之後,孩子仍然存在於parentY內存中。如果它被刪除,並且parentY保存,則拋出EntityNotFoundException
。
我有一個SSCE證明這一點,可以發佈它,如果有必要,但它似乎是一個簡單的問題。
父實體:
@Entity
public class TestParent implements Serializable {
private static final long serialVersionUID = 3572015072906463953L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TestParent_GENERATOR")
@SequenceGenerator(name = "TestParent_GENERATOR", initialValue = 1, sequenceName = "TestParent_SEQUENCE", allocationSize = 1)
private long id;
private String name;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "TestParent_Id")
private Set<TestChild> testChildren = new HashSet<>();
@SuppressWarnings("unused")
private TestParent() {
}
public TestParent(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void addChild(TestChild child) {
this.testChildren.add(child);
}
public void removeChild(TestChild child) {
this.testChildren.remove(child);
}
public TestChild findChild(String childsName) {
for (TestChild testChild : this.testChildren) {
if (testChild.getName().equals(childsName)) {
return testChild;
}
}
return null;
}
}
子實體:
@Entity
public class TestChild implements Serializable {
private static final long serialVersionUID = -1594688339088954284L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TestChild_GENERATOR")
@SequenceGenerator(name = "TestChild_GENERATOR", initialValue = 1, sequenceName = "TestChild_SEQUENCE", allocationSize = 1)
private long id;
private String name;
@SuppressWarnings("unused")
private TestChild() {
}
public TestChild(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
請提供您的實體代碼。 –
'TestChild'是否有關聯到'TestParent'(也許通過一個字段)?發佈的代碼不顯示任何這樣的關係。 – manish
@Eruza,你能查看下面我的答案鏈接的示例應用程序嗎? – manish