JPA JoinColumn vs mappedBy

问题:

有什么区别:

@Entity
public class Company {

    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY)
    @JoinColumn(name = "companyIdRef", referencedColumnName = "companyId")
    private List<Branch> branches;
    ...
}

@Entity
public class Company {

    @OneToMany(cascade = CascadeType.ALL , fetch = FetchType.LAZY, mappedBy = "companyIdRef")
    private List<Branch> branches;
    ...
}

回答:

注释@JoinColumn表示该实体是该关系的owner(即:对应的表具有一个具有引用表的外键的列),而属性mappedBy表示该方面的实体是关系的倒数,所有者驻留在“其他”实体中。这也意味着您可以使用“mappedBy”(完全双向关系)注释的类访问另一个表。
特别地,对于问题中的代码,正确的注释将如下所示:

@Entity
public class Company {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
    private List<Branch> branches;
}

@Entity
public class Branch {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "companyId")
    private Company company;
}

 
 
Code问答: http://codewenda.com/topics/python/
Stackoverflow: JPA JoinColumn vs mappedBy

*转载请注明本文链接以及stackoverflow的英文链接

发表评论

电子邮件地址不会被公开。 必填项已用*标注

28 − 22 =