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

后端 未结 8 2147
日久生厌
日久生厌 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:53

    The annotation @JoinColumn indicates that this entity is the owner of the relationship (that is: the corresponding table has a column with a foreign key to the referenced table), whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity. This also means that you can access the other table from the class which you've annotated with "mappedBy" (fully bidirectional relationship).

    In particular, for the code in the question the correct annotations would look like this:

    @Entity
    public class Company {
        @OneToMany(mappedBy = "company",
                   orphanRemoval = true,
                   fetch = FetchType.LAZY,
                   cascade = CascadeType.ALL)
        private List branches;
    }
    
    @Entity
    public class Branch {
        @ManyToOne(fetch = FetchType.LAZY)
        @JoinColumn(name = "companyId")
        private Company company;
    }
    

提交回复
热议问题