【问题标题】:How to avoid cyclic reference annotating with JPA?如何避免使用 JPA 进行循环引用注释?
【发布时间】:2012-04-24 01:45:41
【问题描述】:

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

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

现在我想避免循环引用,即。 e.一个类别“a”,其父级为“b”,而父级为“a”。

有没有办法在 JPA 中检查带有约束的循环引用?还是我必须自己写一些检查,也许在@PostPersist-annotated 方法中?

这是我的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 ..
}

【问题讨论】:

  • 你为什么需要那个? JPA 会自动检查,不会出现任何问题。你有什么问题?
  • “父母”字段在哪里?您将其称为“mappedBy”

标签: java jpa jpa-2.0


【解决方案1】:

我相信您必须通过代码中的业务规则来检查这一点。为什么不将这些 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;
    }   

}

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

【讨论】:

    【解决方案2】:

    我知道几年后我又回到了这个问题,但是,我遇到了这个问题,遵循了你所有的解决方案,但它对我没有用。但是我找到了使用@JsonIgnoreProperties 的最佳解决方案,它完美地解决了这个问题。事实上,我将@JsonIgnoreProperties 注入到通过如下映射链接的实体类中:https://hellokoding.com/handling-circular-reference-of-jpa-hibernate-bidirectional-entity-relationships-with-jackson-jsonignoreproperties/

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    相关资源
    最近更新 更多