如何避免使用JPA注释循环引用? [英] How to avoid cyclic reference annotating with JPA?

查看:61
本文介绍了如何避免使用JPA注释循环引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一家商店注释域模型(使用JPA 2,使用Hibernate提供程序)。

在商店里,每件产品都可以有Category。每个类别可以被分配到几个超类别和子类别中,这意味着类别"蜡烛"可以将"餐厅"和"装饰"作为父母,将"普通蜡烛"和"多芯蜡烛"作为孩子,等等。

现在我要避免循环引用,即类别"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 ..
}

推荐答案

我认为您必须通过代码中的业务规则进行检查。为什么不在一个单独的实体中分离这些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;
    }   

}

通过这种方式,您可以在保存新实体之前查询任何现有的父子组合。

这篇关于如何避免使用JPA注释循环引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆