我正在为一家商店注释我的域模型(使用 JPA 2,使用 Hibernate Provider)。
商店里的每件产品都可以有一个Category
。每个类别可以分配给多个超级类别和子类别,这意味着“蜡烛”类别可以将“餐厅”和“装饰”作为父类别,将“普通蜡烛”和“多芯蜡烛”作为子类别等。
现在我想避免循环引用,i。 e.以“b”作为其父级的类别“a”,而“b”又以“a”作为其父级。
有没有办法在 JPA 中检查带有约束的循环引用?或者我必须自己写一些支票吗?@PostPersist
- 带注释的方法?
这是我的Category
class:
@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 ..
}
我相信您必须通过代码中的业务规则来检查这一点。为什么不将这些 ManyToMany 映射分离到单独的 Entity 中?例如:
@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;
}
}
这样,您可以在保存新实体之前查询任何现有的父子组合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)