Hibernate Many-To-One Relationship without Primary Key or Join Table
First of all, in a bidirectional association, there is always an owner side, which defines the mapping, and an inverse side, marked by the presence of the mappedBy
attribute.
In a OneToMany association, the owner side is always the many side (PartRelease in your case).
Moreover, a join column, by default, references the ID of the entity it references. Since it's not what you want, you have to specify the referenced column name.
And of course, the RELEASES column must be mapped:
public class GlobalPart extends ModelBase implements Serializable {
@OneToMany(fetch = FetchType.EAGER, mappedBy = "globalPart")
private Set<PartRelease> partReleases;
@Column(name = "RELEASES")
private Long releasesNumber;
}
public class PartRelease extends ModelBase implements Serializable {
@ManyToOne
@JoinColumn(name = "COLLECTION_ID", referencedColumnName = "RELEASES")
private GlobalPart globalPart;
}
Associations are well described in the documentation. You should read it.
Whenever you need to map a @ManyToOne
using a non-Primary Key column on the parent-side, you have to use the referencedColumnName
attribute of the @JoinColumn
annotation.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(
name = "RELEASES",
referencedColumnName = "COLLECTIONGID"
)
I used FetchType.LAZY
for the @ManyToOne
because, by default, FetchType.EAGER
fetching is used, which is very bad for performance.