Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 119 ยท JPA and Hibernate

Entity Relationships

Map JPA relationships the right way - @ManyToOne, @OneToMany, @OneToOne and @ManyToMany, the owning side, mappedBy, cascades and orphanRemoval, with real SQL tables.

Real data is connected. A book has an author, an order has lines, a student takes many courses. In the database those connections are foreign keys and join tables. In Java they are plain references and collections: book.getAuthor(), order.getLines(). JPA's relationship annotations tell the ORM how one world maps onto the other.

Relationships are also where most JPA bugs live. Mixing up the owning side, cascading in the wrong direction or forgetting to update both ends of an association leads to rows with NULL foreign keys, surprise deletes and endless toString() loops. In this lesson you will map all four relationship types, and for each one you will run the real tables behind it on H2, so you always know what SQL your annotations stand for. If entities and @Id are new to you, start with Entities and Hibernate Setup.

The four relationship types

JPA names relationships by how many objects sit on each side:

Annotation Example Stored as
@ManyToOne many books โ†’ one author a foreign key column in the "many" table (book.author_id)
@OneToMany one author โ†’ many books the same foreign key, seen from the other end
@OneToOne one user โ†’ one profile a unique foreign key, or a shared primary key
@ManyToMany many students โ†” many courses a separate join table with two foreign keys

Notice that @ManyToOne and @OneToMany are not two different structures. They are two views of one foreign key. That fact is the key to the whole lesson.

@ManyToOne: the foreign key side

Start with the simplest and most common mapping. Each book points to its author:

Java
@Entity
public class Book {
    @Id @GeneratedValue
    private Long id;

    private String title;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "author_id")
    private Author author;

    // constructors, getters, setters
}

@JoinColumn names the foreign key column; without it, Hibernate derives author_id from the field name and the target's id anyway. optional = false adds a NOT NULL constraint when Hibernate generates the schema and lets it skip a null check. FetchType.LAZY is not the default for @ManyToOne (the default is eager), but it is what you almost always want; Fetching Strategies and the N+1 Problem explains why.

Here are the tables this mapping stands for. Run it and look at what the database refuses.

Java The tables behind ManyToOne and OneToMany

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

There is no "list of books" stored anywhere. An author's books are simply the rows whose author_id matches. Both failures are referential integrity violations. H2 reports 23506 ("parent missing") when a book points at an author that doesn't exist, and 23503 ("child exists") when you try to delete an author while books still point at them. PostgreSQL uses 23503 for both. Keep that second error in mind for the section on cascades.

@OneToMany and mappedBy

To navigate from an author to their books, add a collection on the other side and tell JPA it is the same relationship:

Java
@Entity
public class Author {
    @Id @GeneratedValue
    private Long id;

    private String name;

    @OneToMany(mappedBy = "author")
    private List<Book> books = new ArrayList<>();

    public void addBook(Book book) {
        books.add(book);
        book.setAuthor(this);
    }

    public void removeBook(Book book) {
        books.remove(book);
        book.setAuthor(null);
    }
}

mappedBy = "author" means: "this collection is described by the author field in Book; don't create anything new for it." The side that holds the foreign key (Book.author) is the owning side. The side with mappedBy is the inverse side.

The rule that follows surprises almost everybody once: Hibernate only looks at the owning side when it writes the relationship. Adding a book to author.getBooks() changes nothing in the database unless book.getAuthor() is set too. The inverse collection is a convenience for reading.

The next example imitates what an ORM does at flush time. It writes book rows using book.author, exactly as Hibernate does, and ignores the author's list.

Java Only the owning side is written

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In memory the author has two books, but the first one was saved with author_id NULL. With a NOT NULL column you would get a constraint error instead; without one you get silently orphaned data. The fix is the pair of helper methods shown above: addBook and removeBook update both ends, and the rest of your code only ever calls them.

A @OneToMany without mappedBy is a different, unidirectional mapping. Hibernate then treats the collection as the owner and, unless you add @JoinColumn, creates an extra join table such as author_books. Even with @JoinColumn, it can need extra UPDATE statements to set the foreign keys. Prefer a @ManyToOne on the child, optionally with a mappedBy collection on the parent.

@OneToOne

A one-to-one relationship links exactly one row to one row: a user and their profile, an order and its invoice. The cleanest mapping shares the primary key, so the profile's id is the user's id:

Java
@Entity
public class UserProfile {
    @Id
    private Long id;              // same value as the user's id

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId                       // fill id from user.getId()
    @JoinColumn(name = "user_id")
    private UserAccount user;

    private String bio;
}

With @MapsId, the user_id column is both the primary key and the foreign key. The alternative is a normal foreign key column with a UNIQUE constraint (@JoinColumn(name = "user_id", unique = true)). Both guarantee "at most one profile per user", as the next example shows.

Java Two ways to store a one-to-one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The second insert in each pair fails with 23505, a unique (or primary key) violation. The shared-key version is a little leaner: one less column and one less index, and you can load a profile by the user's id directly.

One-to-one has a performance trap worth knowing now. On the inverse side (@OneToOne(mappedBy = "user") inside UserAccount), Hibernate cannot know whether a profile exists without querying for it, so that side is often loaded eagerly no matter what fetch says. If you only ever go from profile to user, map only that direction.

@ManyToMany and join tables

A student takes many courses and a course has many students. Neither table can hold the foreign key, so the database needs a join table with one row per pair:

Java
@Entity
public class Student {
    @Id @GeneratedValue
    private Long id;
    private String name;

    @ManyToMany
    @JoinTable(name = "enrollment",
        joinColumns = @JoinColumn(name = "student_id"),
        inverseJoinColumns = @JoinColumn(name = "course_id"))
    private Set<Course> courses = new HashSet<>();
}

@Entity
public class Course {
    @Id @GeneratedValue
    private Long id;
    private String title;

    @ManyToMany(mappedBy = "courses")
    private Set<Student> students = new HashSet<>();
}

Here you choose the owner: the side with @JoinTable writes the join table, and the side with mappedBy is read-only for the relationship. Use a Set, not a List. With a List (a "bag"), removing one course makes Hibernate delete every join row for that student and re-insert the remaining ones.

Join tables often grow extra columns: the date of enrollment, a grade, who approved it. @ManyToMany can't hold those. The moment the link has data of its own, promote it to a real entity (Enrollment) with two @ManyToOne fields, and replace the many-to-many with two one-to-many relationships.

Java A join table, queried from both sides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The composite primary key (student_id, course_id) makes duplicate enrollments impossible, which is exactly what a Set promises in Java. In JPA you would map this Enrollment entity with an @EmbeddedId (or simply a surrogate id plus a unique constraint on the pair).

Cascades

A cascade passes an operation from one entity to its associated entities. With cascade = CascadeType.PERSIST on Order.lines, calling entityManager.persist(order) also persists every new line. The available types are PERSIST, MERGE, REMOVE, REFRESH, DETACH and ALL (all of them).

Java
@Entity
public class PurchaseOrder {
    @Id @GeneratedValue
    private Long id;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<OrderLine> lines = new ArrayList<>();

    public void addLine(OrderLine line) { lines.add(line); line.setOrder(this); }
    public void removeLine(OrderLine line) { lines.remove(line); line.setOrder(null); }
}

Cascade from a parent that owns its children's life: an order and its lines, a post and its images. Two rules keep you out of trouble:

  • Never cascade from child to parent. @ManyToOne(cascade = CascadeType.REMOVE) on Book.author means deleting one book deletes the author, and then Hibernate tries to delete all their other books too.
  • Don't put REMOVE (or ALL) on @ManyToMany. Removing a student would delete the shared courses that other students still take.

JPA cascades happen in Java, entity by entity. The database has its own ON DELETE CASCADE on foreign keys, which deletes child rows in one statement without loading them. They solve different problems; JPA won't know about rows the database deleted behind its back, so if you use database cascades, don't keep those children loaded in the same persistence context.

orphanRemoval

orphanRemoval = true adds one more rule: a child that is removed from the collection is deleted, even though nobody called remove() on it. Compare that to the owning-side rule from earlier: without orphan removal, removing a line from the inverse-side list changes nothing in the database.

The simulation below shows what the flush does in both modes.

Java Removing a child with and without orphanRemoval

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without orphan removal the lantern is still in the database, so it would come back the next time the order is loaded. With it, Hibernate issues a DELETE. Use orphan removal only for children that cannot exist without their parent; a Book removed from an author's list should probably not be deleted from the library.

Map and ordered collections, interceptors and cache regions

Four more tools complete the mapping picture. They matter once an application has real data: collections that are maps, collections whose order must be kept, code that must observe every save, and a second-level cache that does not serve stale data.

Map collections: @ElementCollection with @MapKeyColumn

Not every collection is a list. A product may have free-form attributes (color to red, size to XL). A Map of simple values is mapped as an element collection with a key column, and Hibernate creates a collection table with three columns: the owner's id, the key and the value.

Java
@Entity
public class Product {
    @Id @GeneratedValue private Long id;
    private String name;

    @ElementCollection
    @CollectionTable(name = "product_attribute", joinColumns = @JoinColumn(name = "product_id"))
    @MapKeyColumn(name = "attr_name", length = 40)
    @Column(name = "attr_value")
    private Map<String, String> attributes = new HashMap<>();
}

A map of entities works too. @OneToMany @MapKey(name = "isbn") builds a Map<String, Book> whose key is a property of the child, so no extra column is needed. Use @MapKeyEnumerated when the key is an enum and @MapKeyTemporal for dates.

Keeping order: @OrderBy and @OrderColumn

A List has an order in memory, but a relational table has none, so you must say how the order is recovered. There are two different tools:

@OrderBy("title ASC") @OrderColumn(name = "position")
Order comes from a property of the child, via ORDER BY when loading an extra integer column that Hibernate maintains
Extra column in the table no yes (the index, starting at 0)
Adding or reordering elements no cost may update the position of many rows
Use when the order is a natural property (title, date) the user decides the order (a playlist, a checklist)
Java
@OneToMany(mappedBy = "playlist", cascade = CascadeType.ALL, orphanRemoval = true)
@OrderBy("addedAt DESC, id")                  // sorted by a property when loaded
private List<Entry> entries = new ArrayList<>();

@ElementCollection
@CollectionTable(name = "checklist_step", joinColumns = @JoinColumn(name = "checklist_id"))
@OrderColumn(name = "position")               // order stored in the database
@Column(name = "step_text")
private List<String> steps = new ArrayList<>();

Remember that @OrderBy takes property names (or ASC/DESC words), while @OrderColumn creates a physical column. The program below creates the tables these mappings produce on H2 and shows what happens when you move one step up in the @OrderColumn list.

Java The tables behind a Map and an @OrderColumn list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Moving one element to the top rewrote every row. For long lists that change order often, store a sparse sortKey on a real entity (for example 1000, 2000, 3000) so you only update one row.

Interceptors and event listeners

JPA's @PrePersist and @PreUpdate methods live inside one entity class. Sometimes you need to observe every entity in one place: audit logging, setting a tenant id, blocking writes to a read-only table. Hibernate offers two hooks for this.

An Interceptor is a single object registered for a whole SessionFactory (or one session). It is notified as entities are loaded, saved, flushed and deleted, and it may change the property values before they are written:

Java
public class AuditInterceptor implements Interceptor {

    @Override
    public boolean onFlushDirty(Object entity, Object id, Object[] currentState, Object[] previousState,
                                String[] propertyNames, Type[] types) {
        if (entity instanceof Auditable) {
            for (int i = 0; i < propertyNames.length; i++) {
                if ("updatedAt".equals(propertyNames[i])) {
                    currentState[i] = Instant.now();            // change the value that will be written
                    return true;                                // true = we modified the state
                }
            }
        }
        return false;
    }
}
PROPERTIES
hibernate.session_factory.interceptor=com.example.AuditInterceptor

Interceptor has default (empty) methods, so implement only the ones you need. The exact method names and signatures (for example onSave/onPersist) differ between Hibernate versions, so look at the Javadoc of the version you use. A shared interceptor must be thread-safe, because one instance serves all sessions.

Event listeners are the lower-level, more powerful alternative. Hibernate fires an event for every operation (PRE_INSERT, POST_UPDATE, PRE_DELETE, LOAD, ...), and you register a listener for an event type through an Integrator or the EventListenerRegistry. Interceptors are simpler; listeners can veto an operation or see more context. For common needs, higher-level tools exist: Hibernate Envers for history and Spring Data's auditing annotations for timestamps. Keep hooks fast and free of queries, because they run inside flush.

Second-level cache regions: eviction and expiration

The second-level cache is divided into regions, one per cached entity, collection or query. By default, a region is named after the entity class, and you can choose names:

Java
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "reference-data")
public class Country { /* ... */ }

Regions let you give different data different lifetimes, because expiration (time to live, maximum size) is configured per region in the cache provider, not in Hibernate. With Ehcache through JCache, for example:

XML
<cache alias="reference-data">
  <expiry><ttl unit="hours">12</ttl></expiry>
  <heap unit="entries">500</heap>
</cache>
<cache alias="default-update-timestamps-region">
  <expiry><none/></expiry>
  <heap unit="entries">5000</heap>
</cache>

Eviction is removing entries on purpose, which you need when the data changes outside Hibernate (a SQL script, another application, a bulk update):

Java
Cache cache = sessionFactory.getCache();
cache.evictEntityData(Country.class, 5L);        // one row
cache.evictEntityData(Country.class);            // the whole entity region
cache.evictCollectionData("com.example.Order.items");
cache.evictQueryRegions();                        // cached query results
cache.evictAllRegions();                          // everything, the blunt tool

Hibernate evicts automatically for changes that go through it, but bulk JPQL updates and native SQL bypass the persistence context, so cached rows may be stale until they expire. Evict by hand after such operations, keep the TTL short for data that others can change, and cache only what is read often and changes rarely. The program below models regions with their own lifetimes, an eviction after a "bulk update", and hit statistics.

Java Cache regions with different lifetimes, eviction and statistics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The region with the short lifetime paid more database reads, the long-lived one almost none. That trade (freshness against load) is what region settings control. If an entry must never be stale, do not cache it.

Common relationship mistakes

  • toString, equals and hashCode that follow associations. An Author.toString() that prints its books, whose toString() prints the author, recurses until StackOverflowError. Keep these methods to simple fields, and base equals/hashCode on a business key or the id (with a constant hashCode), never on collections. The same loop hits JSON serialization; see Advanced Jackson and, better, return DTOs instead of entities.
  • Replacing a managed collection. author.setBooks(new ArrayList<>(...)) swaps out Hibernate's tracked collection; with orphanRemoval this throws an error. Modify the existing collection (clear(), add()) instead.
  • Forgetting the helper methods. Every bidirectional association needs one place that sets both sides. Make the setters private or package-private if you can.
  • Mapping every association both ways. Bidirectional mappings cost code and memory. Start with @ManyToOne only and add the collection when you really navigate that way.
  • Large @OneToMany collections. An author with 50 books is fine. A Customer.orders with 200,000 rows is not a collection you ever want to load; use a paginated query instead (Querying with JPQL and the Criteria API).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Author.books is @OneToMany(mappedBy = "author"). You call author.getBooks().add(book) but never set book.author, then commit. What is stored?

    Book.author is the owning side and holds the foreign key. The mappedBy collection is ignored when Hibernate writes the relationship. (If the book is new it is saved only if it is persisted or cascaded; either way its author_id is not set.)
  2. 2. Which relationship needs a separate join table in the database?

    Neither side of a many-to-many can hold a single foreign key, so each pair is a row in a join table.
  3. 3. An enrollment now needs a grade and an enrollment date. What is the best mapping?

    @ManyToMany can't map extra columns. A link with its own data is an entity of its own.
  4. 4. PurchaseOrder.lines has cascade = ALL, orphanRemoval = true. You call order.getLines().remove(line) and commit. What happens to the line's row?

    Orphan removal deletes any child that is removed from the parent's collection.
  5. 5. Why is @ManyToOne(cascade = CascadeType.REMOVE) on Book.author dangerous?

    Cascades should flow from a parent to the children whose life it owns. Cascading REMOVE upward deletes shared data.

Summary

  • @ManyToOne and @OneToMany describe one foreign key from its two ends; @ManyToMany uses a join table; @OneToOne uses a unique foreign key or a shared primary key (@MapsId).
  • The side with the foreign key (or @JoinTable) is the owning side; the side with mappedBy is the inverse side. Hibernate writes the relationship from the owning side only.
  • Keep both ends in sync with helper methods like addBook and removeBook.
  • Prefer Set for @ManyToMany, and promote the link to an entity once it has its own columns.
  • Cascade from parent to owned children only; never upward and never REMOVE on many-to-many.
  • orphanRemoval = true deletes children removed from the collection.
  • Keep toString, equals and hashCode away from associations.

Next: Querying with JPQL and the Criteria API shows how to load exactly the entities and values you need.