【问题标题】:Slightly more complex ManyToMany relationship in HibernateHibernate 中稍微复杂的多对多关系
【发布时间】:2012-07-30 03:19:39
【问题描述】:

我的数据库中有以下表格: 表:实体 表:国家 加入表:countries_entities

实体和国家之间是多对多的关系,我在 Entity.hbm.xml 中这样定义:

<set name="country" table="countries_entities" cascade="all">
   <key column="entity_id" />
      <many-to-many column="country_id" class="pikefin.hibernate.Country" />
</set>

这是连接表国家实体的结构:

default_country 字段用于在实体与多个国家/地区关联时指定默认国家/地区。我的问题是,我在hibernate中表示这个的合适方式是什么?我想蛮力的方法是使用 CountryEntity.hbm.xml 的配置文件创建一个全新的映射,但我认为通过以某种方式扩展现有的多对多关系可能会有更优雅的方法。

【问题讨论】:

    标签: java database hibernate orm


    【解决方案1】:

    我发现,当您需要其他字段时,创建一个辅助类来表示关联会很有帮助:

    @Embeddable
    public class CountryAssociation {
       ...
       private Country country;
    
       ...
       private boolean defaultCountry;
    }
    

    然后使用@ElementCollection:

     @ElementCollection
     @CollectionTable(name = "country_entities", joinColumns = @JoinColumn(name = "entity_id"))    
     private Set<CountryAssociation> countries;
    

    我也会去掉关联中的 id 字段,因为这种类型的映射并不真正需要它。

    我的 XML 映射有点生疏,但你也可以用 xml 表示这个映射。

    我相信 xml 会是这样的:

    <set name="countries" table="country_entities">
      <key column="entity_id" />
      <composite-element class="CountryAssociation">
          <property name="country" />
          <property name="defaultCountry" />
      </composite-element>
    </set>
    

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 2015-09-07
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多