我可能做錯了什么,但我不知道是什么。 我有2個表,其中有2個物體,其映射關系如下
public class Parent {
private long id;
private List<ChildBase> childs;
public Parent(){
this.childs = new ArrayList()。
}
ArrayList (;)
public abstract class ChildBase {
protected long id;
.Exclude
protected 父母親。
public ChildBase(Parent parent){
this.parent = parent。
}
}
。
一旦我試圖通過以下測驗斷開父代與子代的連接,問題就出現了:
@Test
public void test(){
Parent parent = new Parent()。
MyChild child1 = new MyChild("a"/span>, parent)。)
MyChild child2 = new MyChild("a", parent)。)
parent.getChilds.add(child1)。
parentRepository.save(parent);
parent.getChilds.remove(child1);
parent.getChilds.add(child2);
parentRepository.save(parent)。
}
我希望在 "childs "表中只看到第二條孩子的記錄,但我看到他們都在。
編輯:
我也試過在第二次保存前從孩子那里參考null,像這樣:child1.setParent(null)。 它也沒有幫助
uj5u.com熱心網友回復:
這是一個雙向的關系,MyChild分別是ChildBase是你的關系的擁有方。
為了觸發移除孤兒,你也必須child1.setParent(null)。
更新:做了一個聊天中提供的設定。這里有一些類,它作業得非常好。
@Entity
@EntityListeners(AuditingEntityListener.class)
@Table(name = "parent")
public class Parent {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@JsonIgnore
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
@LazyCollection(LazyCollectionOption.FALSE)
@Getter
private List<ChildBase> childs;
public Parent(){
this.childs = new ArrayList<>()。
}
@Entity
@Table(name = "childs")
@Getter
@Setter
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Accessors(chain = true)
@NoArgsConstructor
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public abstract class ChildBase {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@EqualsAndHashCode.Include
protected long id;
@JoinColumn(nullable = false)
@ManyToOne
@ToString.Exclude
protected 父母親。
public ChildBase(Parent parent){
this.parent = parent。
}
@Entity
@NoArgsConstructor
@Getter
@Setter[/span
@Accessors(chain = true)
public class MyChild extends ChildBase {
@Column(name = "name")
private String name;
public MyChild(String name, Parent parent) {
super(father);
this.name = name。
}
而這里是測驗。執行后,資料庫中只有childB。
@Test
void test() {
Parent parent = new Parent()。
MyChild child1 = new MyChild("childA", parent)。)
MyChild child2 = new MyChild("childB", parent)。)
parent.getChilds().add(child1)。
parentRepository.save(parent);
parent.getChilds().remove(child1); // first remove
child1.setParent(null); //set parent null
parent.getChilds().add(child2)。
parentRepository.save(parent)。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/327147.html
標籤:
