2009-07-23 106 views
0
@Entity 
public class Parent { 
    @Id 
    @GeneratedValue(strategy=GenerationType.TABLE) 
    int id; 

    @OneToMany(cascade=CascadeType.REMOVE) 
    List<Item> children = new ArrayList<Child>(); 
} 

@Entity 
public class Child { 
    @Id 
    @GeneratedValue(strategy=GenerationType.TABLE) 
    int id; 
} 

正如您在上面看到的,我有一個父對象與子對象之間的OneToMany關係。如果我刪除父項的一個實例,則所有的子項也將被刪除。有沒有一種方法可以讓它反過來工作?JPA:反向級聯刪除

Parent p = new Parent(); 
Child c = new Child(); 
p.children.add(c); 

EntityManager.persist(p); 
EntityManager.persist(c); 

EntityManager.remove (c); 

此代碼無一例外地運行,但是當下次加載p時,會附加一個新的子代。

回答

2

如果你想刪除從兩側工作,你需要定義ParentChild之間的雙向關係:

// in Parent 
@OneToMany(cascade=CascadeType.REMOVE, mappedBy="parent") 
List<Item> children = new ArrayList<Child>(); 

// in Child 
@ManyToOne 
Parent parent;