2012-04-11 112 views
1

我註釋了我的商店域模型(使用JPA 2,使用Hibernate Provider)。如何避免使用JPA進行循環引用註釋?

在店裏每一件產品都可以有一個Category。每個類別可以分配到幾個超類別和子類別,這意味着類別「蠟燭」可以作爲父母具有「餐廳」和「裝飾」,兒童等可以具有「普通蠟燭」和「多燭芯蠟燭」。

現在我想避免循環引用,我。即以「b」作爲其父母的類別「a」,其又以「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 .. 
} 
+0

你爲什麼需要這個? JPA會自動檢查並且不會遇到任何問題。你有什麼問題呢? – 2012-04-11 17:56:03

+0

「父母」字段在哪裏?你稱它爲「mappedBy」 – DataNucleus 2012-04-12 06:46:24

回答

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; 
    } 

} 

通過這種方式,您可以在保存新實體之前查詢任何現有的父 - 子組合。