2016-03-23 11 views
0

JPA 2.1でHibernateを使用していて、2つのサブエンティティでエンティティを定義したいとします。私の問題は、1つのMemberFieldとDiscriminatorColumnという2つの列を持つUniqueConstraintを定義したいということです。JPAエンティティの継承とDiscriminatorColumnのユニーク制約

EDIT:ニコラスの答えは、私が非抽象に抽象から親クラスの種類を変え、私の特定の問題を解決しましたので。

私のコードは次のようになります。

@Entity 
@Inheritance 
@DiscriminatorColumn(name = "TYPE") 
@Table(name = "EXAMPLE", uniqueConstraints = @UniqueConstraint(columnNames = { "TYPE", "NAME" })) 
public class ExampleParent extends AbstractEntity 
{ 
    private static final long serialVersionUID = 68642569598915089L; 

    @Column(name = "NAME", nullable = false, length = 30) 
    @NotNull 
    private String name; 

    ... 

} 

子供1

@Entity 
@DiscriminatorValue("TYPE1") 
public class Example1 extends ExampleParent 
{ 
    private static final long serialVersionUID = -7343475904198640674L; 

    ... 

} 

子供2

@Entity 
@DiscriminatorValue("TYPE2") 
public class Example2 extends ExampleParent 
{ 
    private static final long serialVersionUID = 9077103283650704993L; 

    ... 

} 

Example1とExample2の2つのオブジェクトを同じ名前で永続化できるようにするために、ExampleParentの名前にUniqueConstraintは必要ありません。次のコードは、それを説明する必要があります。

@Autowired 
Example1Repository example1Repo; 

@Autowired 
Example2Repository example2Repo; 

Example1 example1 = new Example1(); 
example1.setName("example"); 
example1Repo.save(example1); 

Example2 example2 = new Example2(); 
example2.setName("example"); 
example2Repo.save(example2); 

をだから私の目標は、2つの列のUniqueConstraintを設定することですが、私は実際にDiscriminatorColumn、私のExampleParentのフィールドを使用します。 DiscriminatorColumnと名前の組み合わせは一意である必要があります。

私のコードが機能しないので、私のオプションは何ですか?

+0

上記のコードでは、ConstraintViolationExceptionを取得しますか? Example1とExample2を同じ名前で挿入することはできませんか? –

+0

@ oliv37はい私はConstraintViolationExceptionを取得します:キーの重複したエントリ '例' ... – shinchillahh

答えて

1

抽象基本クラスを使用している場合は、@Inheritanceの代わりに@MappedSuperclass注釈を使用すると思います。

@MappedSuperclassは多形性に優れています。私は@Inheritenceが多型をサポートしているとは思わない。

+0

まず、あなたの答えに感謝します。あなたは正しいです:私の場合、 '@ MappedSuperclass'を使うほうがいいです。なぜなら私は親クラスのEntityを持っていないからです。それにもかかわらず、私は元の問題を解決する方法を自分自身に求めています。メンバーフィールドの '@ UniqueConstraint'と' @ DiscriminatorColumn'を組み合わせることは可能ですか? – shinchillahh