我正在實施分類系統,其中一個類別通常會有幾個子類別,而一個子類別至少有一個父類別,但肯定會有子類別有多個父類的情況。雙向@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_id
2
而不是1
。
任何人都可以闡明我遇到的任何/兩個問題?
我有過的第一個。似乎是一個錯誤。關於第二個,我認爲你還必須做subcat2.getCats()。remove(category)?既然它是雙向的 –