Issue
In this part of the page on Baeldung, in class CourseRegistration
he is not using @MapsId("id")
and he is not even using "referencedColumnName"
in the JoinColumn
annotation. This was not the case with previous examples on this page. I feel that MapsId
and JoinColumn
with referencedColumnName
should have been used. If not why? He has used the above in all other examples in the same page.
Solution
I feel that MapsId and JoinColumn with referencedColumnName should have been used. If not why? He has used the above in all other examples in the same page.
In the example that you provided he uses the mappedBy
attribute on the other side of the relationship, where OneToMany
exists. This mappedBy attribute provides necessary information to JPA to understand how those 2 entities are related. Keep in mind entity fields represent columns in database and JPA knows what those columns are.
The entity that uses the mappedBy
indicates that the other entity on the other side is the owner of that relationship between those 2 entities.
@ManyToOne
does not have a mappedBy
attribute since by default when you have @OneToMany
together with @ManyToOne
it is the side that has the @ManyToOne
that is the owner of the relationship. So no mappedBy
exists on @ManyToOne
to short circuit this default mechanism.
But there is a way of making the entity that has the @ManyToOne
to be the owner of the relationship. You have to also put above @ManyToOne
the @JoinColumn(name = "ref", referencedColumnName = "ref2")
To sum up the example that you point to, uses the default mechanism where the side with the @ManyToOne
is the owner of the relationship, and that is indicated directly from the other side with the mappedBy attribute on @OneToMany
.
Bonus
@JoinColumn(name = "student_id")
without referencedColumnName
is used not to indicate the owner side of the relationship but just so the JPA is informed that the extra column that would be used as a foreign key would not have the same name as the field of the entity has. So it is just used to override the foreign key column name that JPA will use as foreign key which will not be the same with the java field name.
As for @MapsId
check this answer to understand better how it is used
Answered By - Panagiotis Bougioukos
Answer Checked By - Candace Johnson (JavaFixing Volunteer)