Hibernate / JPA:同一属性上的ManyToMany和OneToMany关系

时间:2014-01-11 23:59:50

标签: java hibernate jpa

我在将ManyToMany与OneToMany关系组合时遇到问题。

我有条目和类别。每个条目都有一个主要类别和0 .. *子类别。

这是我的实施:

public class Entry extends AbstractEntity {
    [...]

    private Category mainCategory;

    @ManyToMany(targetEntity = hello.Category.class)
    private Set<Category> subCategories;

    [...]
}

public class Category extends AbstractEntity {
    [...]

    @ManyToMany(targetEntity = hello.Entry.class, mappedBy = "subCategories")
    private Set<Entry> entries;

    [...]
}

ManyToMany关系功能正常,但我不知道如何实现OneToMany关系。

1 个答案:

答案 0 :(得分:2)

您无法在单个属性上定义两个单独的映射。它应该包含的数据没有明确定义。它是否应包含由subCategories字段或mainCategory或两者映射的条目?由于所有用例都没有明智的答案,JPA不允许这样的多个注释。

但是,您可以添加与一对多关系的反向(非拥有)一侧相对应的字段。

像这样定义:

public class Category ...

  @ManyToOne(mappedBy="mainCategory")
  private Set<Entry> entriesHavingThisCategoryAsMain;

我无法想出反面的更好名称,所以请使用你的上下文:)

编辑:除了在不同的包中有多个targetEntityCategory个实体外,您无需为类型化的集合定义Entry属性。

相关问题