JoinColumn VS mappedBy

What is the difference between:

@Entity
public class Company {

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

and

@Entity
    public class Company {

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


Answer:
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.

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

@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;
}


reference URL: http://stackoverflow.com/questions/11938253/jpa-joincolumn-vs-mappedby

对于mappedBy复习:
a) 只有OneToOne,OneToMany,ManyToMany上才有mappedBy属性,ManyToOne不存在该属性;
b) mappedBy标签一定是定义在the owned side(被拥有方的),他指向the owning side(拥有方);
c) mappedBy的含义,应该理解为,拥有方能够自动维护 跟被拥有方的关系;


   当然,如果从被拥有方,通过手工强行来维护拥有方的关系也是可以做到的。
d) mappedBy跟JoinColumn/JoinTable总是处于互斥的一方,可以理解为正是由于拥有方的关联被拥有方的字段存在,拥有方才拥有了被 拥有方。mappedBy这方定义的JoinColumn/JoinTable总是失效的,不会建立对应的字段或者表

你可能感兴趣的:(JoinColumn,mappedBy,jointable)