0

データベースに次のテーブルがあります: テーブル: エンティティ テーブル: 国 結合テーブル: 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>

結合テーブルcountries_entitiesの構造は次のとおりです。

スクリーンショット

default_country フィールドは、エンティティが複数の国に関連付けられている場合に、デフォルトの国を指定するために使用されます。私の質問は、休止状態でこれを表現する適切な方法は何ですか? 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 に答える