ローマンの回答では、必ずしもテーブル名である必要はありません。本当にそこにある考えは弁別者のそれです。
したがって、テーブルに関しては、これは次のようになります。
create table house ( id .., ..., primary key (id) )
create table user ( id .., ..., primary key (id) )
create table car ( id .., ..., primary key (id) )
create table comment( id ..., commenter ..., commented_id ..., commented_type ... )
このような一連の関係に差別を適用する方法はいくつかあります。
1つは、コメント自体を階層にして、識別子ベースのサブクラス化を使用できることです。このアプローチの短所は、サブクラスが完全に無価値であり、永続性のニーズのみを提供することです。このアプローチの長所は、どのJPAプロバイダーでも機能することです。このアプローチを使用するには、次のようにします。
@Entity
@Table( name="comment" )
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="commented_type")
public abstract class Comment {
@Id
@Column( name="id" )
private Long id;
...
}
@Entity
public class HouseComment extends Comment {
@ManyToOne
@JoinColumn(name="commented_id")
private House getHouse();
...
}
etc...
私が言ったように、ちょっと醜い。
Hibernateは、特にこれを処理するための他のオプションを提供します。たとえば、「任意の」マッピングの概念を使用すると、次のようになります。
@Entity
@Table( name="comment" )
public class Comment {
@Id
@Column( name="id" )
private Long id;
@Any( metaColumn = @Column( name="commented_type" ) )
@AnyMetDef(
idType = "long"
metaValues = {
@MetaValue( value="C", targetEntity=Carclass ),
@MetaValue( value="H", targetEntity=House.class ),
@MetaValue( value="U", targetEntity=User.class )
}
)
pubic Commentable getCommentTarget { ... }
}
public interface Commentable {
...
}
@Entity
public House implements Commentable {
...
}
etc...