2016-10-14 15 views
0

我正在實施分類系統,其中一個類別通常會有幾個子類別,而一個子類別至少有一個父類別,但肯定會有子類別有多個父類的情況。雙向@ManyToMany不會從連接表xx_yy與CascadeType刪除記錄.ALL

這就是爲什麼我選擇ManyToMany的方法。

所以,Category

public class Category implements Serializable { 

    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Basic(optional = false) 
    @Column(name = "cat_id", nullable = false) 
    private Integer catId; 
    ....  
    @ManyToMany(cascade = CascadeType.ALL) 
    @JoinTable(
     name = "cats_subcats", 
     joinColumns = @JoinColumn(name = "cat_id"), 
     inverseJoinColumns = @JoinColumn(name = "subcat_id") 
    ) 
    private Set<Subcategory> subcats; 
    .... 

Subcategory

public class SubCategory implements Serializable { 

    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Basic(optional = false) 
    @Column(name = "subcat_id", nullable = false) 
    private Integer subcatId; 
    .... 
    @ManyToMany(cascade = CascadeType.ALL, mappedBy = "subcats") 
    private Set<Category> cats; 
    .... 

這種設置工作,它創建的連接表,插入我的兩個虛擬subcats,並且還創建了兩個結合記錄連接表。

然後我開始測試它在不同場景下的表現。

首先,我想從三個子類別的現有類別中刪除一個子類別。

我管理的bean:

.... 
@PostConstruct 
    public void init() { 

    category = new Category(); 
    category.setName("Programmatically added ctg"); 
    category.setSlug("programmatically-added-crg"); 

    Set<Subcategory> subcats = new HashSet<>(2); 

    Subcategory subcat = new Subcategory(); 
    subcat.setName("Subcat one"); 
    subcats.add(subcat); 

    Subcategory subcat2 = new Subcategory(); 
    subcat2.setName("Subcat to be removed"); 
    subcats.add(subcat2); 

    Subcategory subcat3 = new Subcategory(); 
    subcat3.setName("The most recent subcat"); 
    subcats.add(subcat3); 

    category.setSubcats(subcats); 

    // this initially saves both the cat and the subcats 
    ctgService.save(category); 
    categories = ctgService.getAll(); 

    // now I remove one of the three subcats 
    category.getSubcats().remove(subcat2); 

    // this is a method belonging to my service (EJB) 
    ctgService.update(category); 

    // upon re-fetching, I can see in my DB that the subcat has not been removed 
    categories = ctgService.getAll(); 
} 
.... 

我得到了它的(在Category實體)@ManyToMany(cascade = CascadeType.ALL)到​​變化的工作。

事實上,它會根據需要刪除子卡,但是...當我查看我的類別時(這個場景中只有一個) - 我可以看到它已被重新插入,因爲它現在有cat_id2而不是1

任何人都可以闡明我遇到的任何/兩個問題?

+0

我有過的第一個。似乎是一個錯誤。關於第二個,我認爲你還必須做subcat2.getCats()。remove(category)?既然它是雙向的 –

回答

0

我想你想「orpahnremoval」,但它不提供@ManyToMany

How do I delete orphan entities using hibernate and JPA on a many-to-many relationship?

+0

我已經知道'orphanRemoval = true'(謝謝),但正如你所指出的,很遺憾這裏不可用。然而,正如我在問題結束時所說的那樣,如果我將'CascadeType.ALL'更改爲某些單獨的級聯類型,它會按預期工作,但由於某種原因,我的類別的id增加1(就好像它是第一個刪除,然後重新創建,但不會將自動增量值重置爲1。 – developer10