2013年10月25日金曜日

単一テーブル継承(Single Table Inheritance)

Hibernateの@Entityを実装している時に、RDBの特定のカラム値を元にポリモーフしたサブクラスを割り当てたい。つまり、抽象クラスを@Entityにして、サブクラスを実装するにはどうしたら良いか調べた。

あっさりとJPA仕様にやり方が書いてあるのを見つけたところ、どうやらSingle Table Inheritance(単一テーブル継承)というやり方がある事が分かった。

そのやり方をWikiから抜粋:

Single Table Inheritance[edit]

Single table inheritance is the simplest and typically the best performing and best solution. In single table inheritance a single table is used to store all of the instances of the entire inheritance hierarchy. The table will have a column for every attribute of every class in the hierarchy. A discriminator column is used to determine which class the particular row belongs to, each class in the hierarchy defines its own unique discriminator value.

Example single table inheritance table in database[edit]

PROJECT (table)
IDPROJ_TYPENAMEBUDGET
1LAccounting50000
2SLegalnull

Example single table inheritance annotations[edit]

@Entity
@Inheritance
@DiscriminatorColumn(name="PROJ_TYPE")
@Table(name="PROJECT")
public abstract class Project {
  @Id
  private long id;
  ...
}
@Entity
@DiscriminatorValue("L")
public class LargeProject extends Project {
  private BigDecimal budget;
}
@Entity
@DiscriminatorValue("S")
public class SmallProject extends Project {
}


ポイントは@DiscripnatorColumnを抽象クラスで指定して、@DiscriminatorValueを実装クラスで教えてあげる。これはかなり便利。



0 件のコメント:

コメントを投稿