JPA:可嵌入类中的外键 [英] JPA: Foreign key in embeddable class

查看:87
本文介绍了JPA:可嵌入类中的外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况要解决,但无法正常工作(尝试了Hibernate和EclipseLink):

I have the following situation to solve, but could not get it work (tried Hibernate and EclipseLink):

Table_1:
    Column_A is Primary Key
    ... some other columns do follow

.

Table_2:
Column_x is Primary Key and is Foreign Key to Table_1.Column_A
Column_y is Primary Key and is Foreign Key to Table_1.Column_A
Column_z is Primary Key

因此,表2具有复合主键.

Thus, table 2 has a composite primary key.

我试图通过以下方式实现它:

I tried to realize it the following way:

class Table_1 {
  @Id int Column_A;
}

.

class Table_2 {
  @EmbeddedId PK key;

  @Embeddable class PK {
    @OneToOne(targetEntity=Table_1.class)
    @JoinColumn(name="Column_x",referencedColumnName="Column_A")
    int Column_x;

    @OneToOne(targetEntity=Table_1.class)
    @JoinColumn(name="Column_y",referencedColumnName="Column_A")
    int Column_y;

    int Column_z;

    public boolean equals(Object O) { ... }
    public int hashCode() { ... } 
  }
}

但是,当我运行时,我从EclipseLink那里得到了提示,即@Embeddable中我只能使用基本"注释.因此,我的问题是如何解决上述情况?

However, when I run, I get the hint from EclipseLink that in @Embeddable I may only use "basic" annotations. Thus, my question is how to solve the above drawn scenario?

我无权访问Table_1类的源代码,但必须按原样使用它.另外,很可能会有更多的类/表为Table_1建立外键.

I do not have access to the source code of class Table_1, but must use it as it is. Also, it will be very likely that there may be more classes / tables establishing foreign keys to Table_1.

推荐答案

使用@IdClass.

Use an @IdClass.

看, http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0

@IdClass(PK.class)
class Table_2 {
    @Id
    @OneToOne(targetEntity=Table_1.class)
    @JoinColumn(name="Column_x",referencedColumnName="Column_A")
    Table_1 Column_x;

    @Id
    @OneToOne(targetEntity=Table_1.class)
    @JoinColumn(name="Column_y",referencedColumnName="Column_A")
    Table_1 Column_y;

    @Id
    int Column_z;

    public boolean equals(Object O) { ... }
    public int hashCode() { ... } 
  }
}

class PK {
    int Column_x;
    int Column_y;
    int Column_z;
}

这篇关于JPA:可嵌入类中的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆