Whimusical Whimusical - 1 month ago 5x
Java Question

Can @JoinColumn refer to a previously defined field, or otherwise, what is happening here?

I got a code with an Id column and a OneToOne join in my class Thing.

@Column(name = "id")
private Long id;

@JoinColumn(name = "id", referencedColumnName = "id")
private ThingExtension thingExtension;

Is this working like the following?

Thing ThingExtension
------------------- --------------
id (PK,FK) -------------> id
----------------- --------------

or is it creating twice the id field or something?


In this case JPA provider create only one column id.

Another way to do this:

You can use @PrimaryKeyJoinColumn annotation. Remove @JoinColumn and add @PrimaryKeyJoinColumn (without parameters).

From JPA reference:

The PrimaryKeyJoinColumn annotation specifies that a primary key column is to be used as a for-eign key.