本文介紹了如何避免使用JPA注釋循環(huán)引用?的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我正在為一家商店注釋域模型(使用JPA 2,使用Hibernate提供程序)。
在商店里,每件產(chǎn)品都可以有Category
。每個(gè)類別可以被分配到幾個(gè)超類別和子類別中,這意味著類別”蠟燭”可以將”餐廳”和”裝飾”作為父母,將”普通蠟燭”和”多芯蠟燭”作為孩子,等等。
現(xiàn)在我要避免循環(huán)引用,即類別”a”的父級(jí)為”b”,而類別”a”的父級(jí)又為”a”。
有沒有辦法在JPA中檢查帶有約束的循環(huán)引用?或者我必須自己寫一些檢查,也許是用@PostPersist
注釋的方法?
這是我的Category
類:
@Entity
public class Category {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany
private Set<Category> superCategories;
@ManyToMany(mappedBy="superCategories")
private Set<Category> subCategories;
public Category() {
}
// And so on ..
}
推薦答案
我認(rèn)為您必須通過代碼中的業(yè)務(wù)規(guī)則進(jìn)行檢查。為什么不在一個(gè)單獨(dú)的實(shí)體中分離這些ManyToMany映射呢?例如:
@Entity
@Table(name = "TB_PRODUCT_CATEGORY_ROLLUP")
public class ProductCategoryRollup {
private ProductCategory parent;
private ProductCategory child;
@Id
@GeneratedValue
public Integer getId() {
return super.getId();
}
@Override
public void setId(Integer id) {
super.setId(id);
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_PRODUCT_CATEGORY_PARENT", nullable=false)
public ProductCategory getParent() {
return parent;
}
public void setParent(ProductCategory parent) {
this.parent = parent;
}
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="ID_PRODUCT_CATEGORY_CHILD", nullable=false)
public ProductCategory getChild() {
return child;
}
public void setChild(ProductCategory child) {
this.child = child;
}
}
通過這種方式,您可以在保存新實(shí)體之前查詢?nèi)魏维F(xiàn)有的父子組合。
這篇關(guān)于如何避免使用JPA注釋循環(huán)引用?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,