0

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

这是实体和国家之间的多对多关系,我在 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>

以下是连接表 countries_entities 的结构:

截屏

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

4

1 回答 1

1

I've found that when you want additional fields, it's helpful to create a secondary class to represent the association:

@Embeddable
public class CountryAssociation {
   ...
   private Country country;

   ...
   private boolean defaultCountry;
}

And then use @ElementCollection:

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

I'd also get rid of the id field in the association, as it's not really needed with this type of mapping.

My XML mapping is a little rusty, but you can represent this mapping in xml as well.

I believe the xml would be something like this:

<set name="countries" table="country_entities">
  <key column="entity_id" />
  <composite-element class="CountryAssociation">
      <property name="country" />
      <property name="defaultCountry" />
  </composite-element>
</set>
于 2012-07-30T03:34:41.153 回答