Home > Java > javaTutorial > JPA: @JoinColumn vs. mappedBy: When to Use Which?

JPA: @JoinColumn vs. mappedBy: When to Use Which?

DDD
Release: 2024-12-15 22:39:24
Original
861 people have browsed it

JPA: @JoinColumn vs. mappedBy: When to Use Which?

Understanding JPA JoinColumn vs mappedBy

In JPA, the @JoinColumn annotation defines a foreign key column in the current entity that references a column in the referenced entity. Contrastingly, the mappedBy attribute specifies that the current entity is the inverse side of a bidirectional relationship, where the ownership of the foreign key resides in the referenced entity.

Ownership and Inverse Relationships

When using @JoinColumn, the entity with the annotation is considered the "owner" of the relationship. As such, its table will contain the foreign key column linking to the referenced table. On the other hand, the mappedBy attribute signifies that the entity with this annotation is the "inverse" side of the relationship. The ownership of the foreign key resides in the entity referenced by mappedBy.

Annotation Example

Here's an example that illustrates the difference:

@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;
    ...
}
Copy after login

In the first code block, @JoinColumn is used, making Company the owner of the relationship. Company's table will contain the foreign key column "companyIdRef" that references the "companyId" column in the Branch table.

In the second code block, mappedBy is used, making Company the inverse side of the relationship. Branch is now the owner, and its table will contain the foreign key column "companyIdRef" that references Company's "companyId" column.

Bidirectional Relationships

When using mappedBy, you can access the related entity from either side of the relationship, allowing for bidirectional navigation. This is not possible when using @JoinColumn alone, as the foreign key ownership resides with only one entity.

The above is the detailed content of JPA: @JoinColumn vs. mappedBy: When to Use Which?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template