Understanding the Distinction between JoinColumn and mappedBy in JPA
In Java Persistence API (JPA), managing relationships between entities is crucial. Among the key annotations for establishing relationships are @JoinColumn and @mappedBy.
When using @OneToMany annotations for bidirectional relationships, one needs to differentiate between the owning and the inverse side of the relationship. Using @JoinColumn on the owning side indicates that the referenced table has a foreign key column to the corresponding table. In contrast, @mappedBy signifies the inverse side, implying that the other entity acts as the owner of the relationship and has a mapped column referencing the entity using @mappedBy.
Code Example
Consider the following code examples:
@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; ... }
In the first example, Company is the owning side and branches are referenced through the foreign key column companyIdRef. In the second example, Company is the inverse side of the relationship and branches are referenced through the mapped column companyIdRef.
Correct Annotation Usage
For the code provided in the question, the correct annotations should be:
@Entity public class Company { @OneToMany(mappedBy = "company", orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Branch> branches; } @Entity public class Branch { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "companyId") private Company company; }
By using these annotations, a bidirectional relationship is established between Company and Branch, with Company as the inverse side and Branch as the owning side.
The above is the detailed content of JoinColumn vs. mappedBy in JPA: When to Use Which Annotation?. For more information, please follow other related articles on the PHP Chinese website!