java JPA @JoinColumn 加入非主键列时出现问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11386610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 04:53:10  来源:igfitidea点击:

JPA @JoinColumn issues while joining on non primary key columns

javajpa

提问by Bhumir Jhaveri

I want to connect table based on one direction join, here is my code:

我想基于单向连接连接表,这是我的代码:

Class Person {

@id
String person_sk;

int person_id;

String Person_name;

@OneToMany
@joinColumn (name="person_reference_id")
List<address> getAddresses() {}

}

class Address
{

@id
int person_reference_id (referred from Person);

@id
int address_id;

@id
int phone_id;

String street_name, zip_code;

}

Now when I do getAddress, it does not work, because my join is based on person_ref_id and @id (primaryKey) column in Person class is person_sk.

现在,当我执行 getAddress 时,它不起作用,因为我的加入是基于 person_ref_id 的,而 Person 类中的 @id(primaryKey)列是 person_sk。

If I use referencedColumn then also it doesn't work.

如果我使用 referencedColumn 那么它也不起作用。

回答by JMelnik

  1. JPA does not allow references to non-PK columns.

  2. ReferencedColumn property is used to specify join column, when there is a composite PK in referenced table.

  1. JPA 不允许引用非 PK 列

  2. ReferencedColumn 属性用于指定连接列,当被引用表中存在复合 PK 时

How can I make this work??

我怎样才能使这项工作?

Normalize your database to use common PK-FK relationships. If needed - define composite PK.

标准化您的数据库以使用常见的 PK-FK 关系。如果需要 - 定义复合 PK。

回答by James

Unusual data model, you may want to rethink it.

不寻常的数据模型,您可能需要重新考虑一下。

Also, normally it is best to define a @OneToMany using a mappedBy and an inverse @ManyToOne.

此外,通常最好使用mappedBy 和反向@ManyToOne 来定义@OneToMany。

JPA does not directly support your data model, but if you are using EclipseLink, you can define the OneToManyMapping using a DescriptorCustomizer and use whatever foreign keys or join conditions you require.

JPA 不直接支持您的数据模型,但如果您使用 EclipseLink,您可以使用 DescriptorCustomizer 定义 OneToManyMapping 并使用您需要的任何外键或连接条件。