Entity Relationships: OneToMany, ManyToOne, ManyToMany

Harry · 11 Sep 2026 · 11 views

Entity Relationships: OneToMany, ManyToOne, ManyToMany

Relational databases connect tables with foreign keys, and JPA mirrors that with relationship annotations. The join is owned by exactly one side, and getting the ownership right determines which tables get the foreign key columns and join tables.

ManyToOne is the owner

A many-to-one side owning the relationship is the JPA default, and it leads to the simplest schema. An order referencing a customer has a customer_id column, and the owning side is the Order.

@Entity
public class Order {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id")
    private Customer customer;
}

OneToMany with mappedBy

The inverse side uses mappedBy to say the foreign key lives elsewhere. The collection is only a navigation convenience; its contents come from querying the owning side. Keep mappedBy on one-to-many collections and let the many-to-one side hold the real mapping.

@Entity
public class Customer {
    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private List<Order> orders = new ArrayList<>();
}

ManyToMany and join tables

For products and tags, no side owns the key. JPA creates a join table with both ids. Choose which side is temporal via mappedBy on one side. Also decide cascade options: cascading ALL or REMOVE on a many-to-many is rare and dangerous.

Why everyone hits LazyInitializationException

Mark @ManyToOne and collections lazy and access them inside a transaction, or the session is gone when you read the collection. Fetching strategies and DTO projections are the cure; eager loading is a band-aid that bloats queries.

Key Points

  • The many-to-one side owns the foreign key by default.
  • Use mappedBy on the one-to-many inverse side.
  • Many-to-many becomes a join table with both ids.
  • Chain cascade carefully; cascade ALL on collections is usually wrong.
  • Access lazy associations inside transactions to avoid lazy-init exceptions.
Share this post:

Comments (0)

Please login or register to comment.