JPA JoinColumn for foreign keys belonging to the table behind its member entity

▼魔方 西西 提交于 2019-12-12 04:49:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26590339/jpa-joincolumn-for-foreign-keys-belonging-to-the-table-behind-its-member-entity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!