Video in progress
What does mappedBy mean in a @OneToMany and @ManyToOne relationship?
mappedBy marks the inverse side of the relationship: "the foreign key is controlled not by me but by the field on the other side". The FK column lives in the table that has the @ManyToOne.
📖 Answer
@Entity
class Order {
@Id Long id;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderItem> items = new ArrayList<>();
void addItem(OrderItem item) { // we update both sides
items.add(item);
item.setOrder(this);
}
}
@Entity
class OrderItem {
@Id Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "order_id") // the FK is in this table
private Order order;
}
mappedBy = "order" is the name of the order field in the OrderItem class. This side is not the owner.
A common mistake: doing only order.getItems().add(item) and forgetting item.setOrder(order). Hibernate takes the FK from the owner side, so order_id ends up NULL. That's why we write a helper like addItem above.
If you leave out mappedBy entirely, Hibernate treats it as two independent relationships and tries to create an extra join table (order_items).
Sign up to mark studied questions and save your progress.