我正在为一个商店注释我的域模型(使用JPA 2,使用Hibernate Provider)。
在商店里,每件商品都有Category
。每个类别可以分配到几个超级和子类别,这意味着“蜡烛”类别可以将“餐厅”和“装饰”作为父母,“普通蜡烛”和“多灯芯蜡烛”作为儿童等。
现在我想避免循环引用,i。即一个“a”类别,其中“b”作为其父级,而“a”又以“a”作为其父级。
有没有办法在JPA中检查带约束的循环引用?或者我是否必须自己编写一些检查,可能是@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 ..
}
答案 0 :(得分:1)
我相信你必须通过代码中的业务规则来检查这一点。为什么不在单独的实体中分离这些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;
}
}
通过这种方式,您可以在保存新实体之前查询任何现有的父子组合。