I am experiencing an unexpected behavior while performing a jpql query on an entity having a one-to-one relationship with another. The key point is that the relationship is from the primary key of the root entity to a field of the destination entity which is not the ID.
Here is the example:
// root entity
@Entity
@Table(name = "PERSON")
public class Person {
@Id
@Column(name = "PERSON_ID")
private long id;
private String name;
@OneToOne(optional = false)
@JoinColumn(name = "PERSON_ID", referencedColumnName = "PERSON_ID", insertable = false, updatable = false, unique = true)
private Address mainAddress;
...
}
// referenced entity
@Entity
@Table(name = "ADDRESS")
public class Address {
@Id
@Column(name = "ADDRESS_ID")
private long id;
@Column(name = "PERSON_ID")
private long personId;
...
}
The following jpql query:
select p from Person p left join fetch p.mainAddress
Produces the following ORACLE SQL query:
SELECT ... FROM PERSON p LEFT OUTER JOIN ADDRESS a ON p.PERSON_ID = a.ADDRESS_ID
While I expected :
SELECT ... FROM PERSON p LEFT OUTER JOIN ADDRESS a ON p.PERSON_ID = a.PERSON_ID
Basically the attribute of the referencedColumnName = "PERSON_ID" attribute is ignored and the join is performed on the primary key.
Somebody can please explain me why?