A possible answer to my question is located here: How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?
However, the preferable solution (property access) does not work in my case (I got missing column exception - why?)
The model looks like this: Entities Parent
and Child
. Table parent
has column child_id
which is PK
of child
table so it is typical @ManyToOne
relation.
Now the point is, if I fetch Parent
entities, I need to have access to FK
value (aka. PK
of Child
entity) without fetching Child
entities. How can I do that?
I use Annotations
and my mapping looks as follows:
@Entity
@Table(name = "parent")
public class Parent extends AbstractEntity {
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "patent_id", nullable = true)
private Child child;
@Column(name="child_id",insertable=false,updatable=false)
private Integer childId;
public Child getChild() {
return patent;
}
public void setChild(Child child) {
this.child = child;
}
public Integer getChildId(){
return childId;
}
}
And what I want to do is call parent.getChild().getId()
without extra fetches of Child
entity from DB.
According to the answer I have mentioned above, If I moved annotations from field to getter (in Parent
entity am I right?), requested behavior would be out of the box. However, when I move annotations to getter, I get a validation exception that child
column is missing (curious, why child
not child_id
as declared?)
PS: Shown workaround to declare a FK
column as separate field works fine, but I don't think that this is the way it should be done.