indexとかunique-key

indexやunique-keyをHibernateのExportでDDLに反映させるのにちょっと苦労したんでメモ。

  <class name="org.asyrinx.joey.gen.sample1.om.party.entity.Party"  table="party" >
    <id name="partyId" column="party_id" type="long" unsaved-value="0" >
      <generator class="native" />
    </id>

    <property name="partyCode" type="string" column="party_code" length="30" not-null="true" />
    <property name="name" type="string" column="name" length="50" not-null="true" />
    <property name="nameKana" type="string" column="name_kana" length="50" not-null="false" />
    <property name="partyTypeId" type="integer" column="party_type_id"  not-null="true" />

    <component name="keyPartyCode" class="org.asyrinx.joey.gen.sample1.om.party.entity.BaseParty$KeyPartyCode" insert="false" update="false">
      <parent name="parent"/>
      <property name="partyCode" type="java.lang.String" >
        <column name="party_code" unique-key="u_party_1"/> 
      </property>
    </component>


    <component name="keyName" class="org.asyrinx.joey.gen.sample1.om.party.entity.BaseParty$KeyName" insert="false" update="false">
      <parent name="parent"/>
      <property name="name" type="java.lang.String" >
        <column name="name" index="i_party_1"/> 
      </property>
    </component>

    <component name="keyNameKana" class="org.asyrinx.joey.gen.sample1.om.party.entity.BaseParty$KeyNameKana" insert="false" update="false">
      <parent name="parent"/>
      <property name="nameKana" type="java.lang.String" >
        <column name="name_kana" index="i_party_2"/> 
      </property>
    </component>


  </class>

だいたいこんな感じ。
ポイントはcomponentタグで定義されるindexやunique-keyのキーとなるオブジェクト。
insertとupdate属性をfalseにしておかないと、同じ名前のpropertyに対する処理が重複して例外が発生しちゃう。

それからcomponentタグ中のpropertyとそのcolumn。indexとかunique-keyはcolumnに書く。


ちなみにjoey-genは以下のスキーマから上記のxmlを生成します。

    <table name="party" label="パーティ" captionProperty="name" >
      <column name="party_id" required="true" type="BIGINT" primaryKey="true" readonly="true" label="パーティID"/>
      <column name="party_code" required="true" type="VARCHAR" size="30" label="パーティコード" unique="true"/>
      <column name="name" required="true" type="VARCHAR" size="50" label="名前" indexed="true"/>
      <column name="name_kana" required="false" type="VARCHAR" size="50" label="カナ名" indexed="true"/>
      <column name="party_type_id" required="true" type="INTEGER" label="パーティ種別" enum="PartyType"/>
    </table>

この例ではindexやunique-keyはカラムが一個ずつですが、複数指定することも可能です。