Sandah Aung
Sandah Aung

Reputation: 6188

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

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?

Upvotes: 0

Views: 938

Answers (1)

Predrag Maric
Predrag Maric

Reputation: 24423

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.

Upvotes: 1

Related Questions