Hibernate Many-To-One Relationship without Primary Key or Join Table

試著忘記壹切 提交于 2019-11-30 04:53:16

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.

As explained in this article, 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, EAGER fetching is used, which is very bad for performance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!