JPA JoinColumn属于该成员实体后面的表的外键 [英] JPA JoinColumn for foreign keys belonging to the table behind its member entity
问题描述
我有表 table_a
和 table_b
和外键 table_a_id
在 table_a
中引用主键 id
。
现在我有两个JPA实体, A
和 B
。 A
包含对 B
的引用。
public class A {
...
@JoinColumn(name =table_a_id)
private B b;
$
这会抛出异常,表示列 table_a_id
不能在 table_a
中找到。我知道JPA在 table_a
中寻找一个外键 table_a_id
,但是如何解决这个问题而不移动外键 table_a
?
解决方案 @ code> A 和 @JoinColumn
在 B
中。关系的拥有方是外键,在这种情况下是 B
。 mappedBy中的a
是类 B中类型 A
/ code>。
编辑
,当外键在目标表中时,根据这个,如果你把 insertable = false
和 updateable = false @JoinColumn
JPA提供程序在目标表中查找外键。
I have tables table_a
and table_b
and foreign key table_a_id
references the primary key id
in table_a
.
Now I have two JPA entities, A
and B
. A
contains a reference to B
.
public class A {
...
@JoinColumn(name="table_a_id")
private B b;
}
This throws exceptions saying that column table_a_id
cannot be found in table_a
. I know JPA is looking for a foreign key table_a_id
in table_a
but how can I resolve this problem without moving the foreign key to table_a
?
解决方案 You can have @OneToOne(mappedBy = "a")
in A
, and @OneToOne
with @JoinColumn
in B
. The owning side of the relationship is the one where foreign key is, that would be B
in this case. "a"
in mappedBy is the name of the field of type A
in class B
.
EDIT
In case of unidirectional relationship, when foreign key is in target table, according to this, if you put insertable = false
and updateable = false
in @JoinColumn
, that will instruct the JPA provider to look for foreign key in the target table.
这篇关于JPA JoinColumn属于该成员实体后面的表的外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文