2011-01-08 1 views
5

JPA @EmbeddedIdから逆参照を確立できるかどうかを知っていますか?JPAで@EmbeddedIdから逆参照を設定する方法

したがって、たとえばフォーム複雑な組込みIDで

@Entity 
public class Entity1 { 
    @Id 
    @GeneratedValue 
    private String identifier; 

    private Entity1 relationToEntity1; 
    //Left out the getters and setters for simplicity 
} 

そして第二のエンティティのエンティティがあります。この第2のエンティティの1つの部分は、その親エンティティへの参照である。これと同じように:

Exception [EclipseLink-93] (Eclipse Persistence Services - 1.1.0.r3639-SNAPSHOT): 
org.eclipse.persistence.exceptions.DescriptorException 
Exception Description: The table [ENTITY1] is not present in this descriptor. 
Descriptor: RelationalDescriptor(test.Entity2 --> [DatabaseTable(ENTITY2)]) 

@Entity 
public class Entity2 { 
    @EmbeddedId private Entity2Identifier id; 
    //Left out the getters and setters for simplicity. 
} 

@Embedabble 
public class Entity2Identifier { 
    private String firstPartOfIdentifier; 
    private Entity1 parent; 
    //Left out the getters and setters for simplicity. 
} 

私はJPAを経由して、このような構造を保存しようとするデータベースへの(実装は、EclipseLinkのある)私は、フォームのいくつかの例外を取得します

誰かがこのような問題に遭遇し、解決策を持っていましたか?

答えて

4

お探しのIDは派生IDです。 JPA 2.0を使用している場合は、次のように動作します。 Parent全体が、親のPKだけであるPKの一部であることは本当に望ましくありません。

@Entity 
public class Entity1 { 
    @EmbeddedId 
    private ParentId identifier; 

    @OneToOne(mappedBy="relationToEntity1") 
    private Entity2 relationToEntity2; 

    //Left out the getters and setters for simplicity 
} 

@Entity 
public class Entity2 { 
    @EmbeddedId private Entity2Identifier id; 
    //Left out the getters and setters for simplicity. 

    @MapsId("parentId") 
    @OneToOne 
    private Entity1 parent; 

} 

@Embedabble 
public class Entity2Identifier { 
    private String firstPartOfIdentifier; 
    private ParentId parentId; 
    //Left out the getters and setters for simplicity. 
} 
+0

OK。私の例は単純だと思います。親は実際には2つの文字列で構成される複雑な埋め込みIDを持っています。だから私は単にそのIDを参照することができません。 – ali

+1

これも簡単です。エンティティ1でEmbeddedIdを使用するために上記の例を更新しました。 –

+1

@MapsIdが勝者です!とても便利です。 –

1

@EmbeddedId注釈では、複合識別クラスの関係は許可されません。 EmbeddedId JavaDoc

埋め込みIDクラス内で定義されたリレーションシップマッピングはサポートされていません。

は、私はあなたがEntity2Identifierは親に鍵を入れたいことを理解し、しかし、あなたの例では、あなただけの親の主キーを含むのではなく、オブジェクト全体との関係を作成しています。この構築がうまくいっても、複合キーを親の主キーだけでなく親の全状態に設定することになります。

あなたは、単に双方向の関係を確立する簡単な方法を探しているなら、あなたは@OneToOne注釈とmappedBy属性でそうすることができます:注釈のこのセット、JPAで

@Entity 
public class Entity1 { 
    @Id 
    @GeneratedValue 
    private String identifier; 

    @OneToOne(mappedBy="relationToEntity1") 
    private Entity2 relationToEntity2; 
    ... 
} 

@Entity 
public class Entity2 { 

    @OneToOne 
    private Entity1 relationToEntity1; 
    ... 
} 

プロバイダは、双方向の関係としてEntity1.relationToEntity2Entity2.relationToEntity1を適切に処理します。また、デフォルトのカスケード動作(none)とデフォルトの孤立除去動作(none)をオーバーライドすることもできます。詳細は、JavaDocを参照してください。

+0

ご回答ありがとうございます。実際に私はそれを知っています。問題は、主キーが複数の部分で構成されていることです。そのうちの1つは親エンティティです。これは、エンティティを定義する値があることを意味しますが、親のコンテキストでのみ有効です。 – ali

関連する問題