What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

后端 未结 8 2085
日久生厌
日久生厌 2020-11-22 02:35

What is the difference between:

@Entity
public class Company {

    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
    @JoinColumn(name = \"c         


        
8条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 02:42

    Let me make it simple.
    You can use @JoinColumn on either sides irrespective of mapping.

    Let's divide this into three cases.
    1) Uni-directional mapping from Branch to Company.
    2) Bi-direction mapping from Company to Branch.
    3) Only Uni-directional mapping from Company to Branch.

    So any use-case will fall under this three categories. So let me explain how to use @JoinColumn and mappedBy.
    1) Uni-directional mapping from Branch to Company.
    Use JoinColumn in Branch table.
    2) Bi-direction mapping from Company to Branch.
    Use mappedBy in Company table as describe by @Mykhaylo Adamovych's answer.
    3)Uni-directional mapping from Company to Branch.
    Just use @JoinColumn in Company table.

    @Entity
    public class Company {
    
    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
    @JoinColumn(name="courseId")
    private List branches;
    ...
    }
    

    This says that in based on the foreign key "courseId" mapping in branches table, get me list of all branches. NOTE: you can't fetch company from branch in this case, only uni-directional mapping exist from company to branch.

提交回复
热议问题