In object-relational mapping (ORM), bi-directional relationships between entities require careful handling to avoid infinite loops or inconsistent data states. MappedBy is an attribute in JPA and Hibernate annotations that solves this issue.
Understanding the Role of MappedBy:
MappedBy specifies which entity owns the relationship and possesses the foreign key column in the database. It is applied to the non-owning entity's mapping annotation, indicating that the relationship is mapped by the foreign key in the owning entity's table.
Usage Recommendations:
When defining a bi-directional relationship, it is recommended to follow these guidelines:
Example:
In your Airline and AirlineFlight entities, Airline should be the owner of the relationship. The correct annotations would be:
<code class="java">// Airline.java @OneToMany(mappedBy = "airline") public Set<AirlineFlight> getAirlineFlights() { return airlineFlights; } // AirlineFlight.java @ManyToOne @JoinColumn(name = "IDAIRLINE") public Airline getAirline() { return airline; }</code>
Purpose of MappedBy:
MappedBy serves two primary purposes:
The above is the detailed content of How Does `MappedBy` in JPA and Hibernate Prevent Data Inconsistencies in Bi-directional Relationships?. For more information, please follow other related articles on the PHP Chinese website!