JPA and Hibernate

The previous pages wrote by hand everything that moves objects in and out of tables: DAOs, mapping DAOs, a Proxy for lazy loading, the identity map, version checks. An ORM (object-relational mapper) does all of it from annotations on the classes. JPA (Jakarta Persistence) is the standard Java API for this, and Hibernate is its most used implementation. This page maps the restaurant domain with modern JPA annotations, and shows from Hibernate's own SQL log what each annotation makes it do.

Everything here was run with Hibernate ORM 6.6 on Java 21 against PostgreSQL 17, with hibernate.show_sql on. The Hibernate: lines are its output.

What the ORM replaces

Written by hand In JPA
DTO / bean an @Entity class
DAO with CRUD EntityManager.persist, find, remove, and queries
readByFK to fill a collection @OneToMany
mapping DAO for N:N @ManyToMany with @JoinTable
Proxy subclass for lazy loading generated by Hibernate at runtime
identity map the persistence context
update() calls dirty checking at commit
version check in UPDATE ... WHERE version = ? @Version
IdBroker / reading generated keys @GeneratedValue

The ideas are the same as in mapping objects to tables and loading related data. Knowing them is what makes the ORM's behaviour predictable.

Setup

An application declares a persistence unit (its entity classes and connection settings), and creates one EntityManagerFactory for it at startup. Each unit of work gets an EntityManager, the object that loads and saves entities.

<!-- META-INF/persistence.xml -->
<persistence-unit name="restaurants">
    <class>demo.Restaurant</class>
    <class>demo.RestaurantTable</class>
    <!-- ... -->
    <properties>
        <property name="jakarta.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/restaurants"/>
        <property name="jakarta.persistence.jdbc.user" value="app"/>
        <property name="jakarta.persistence.jdbc.password" value="..."/>
        <property name="hibernate.show_sql" value="true"/>
    </properties>
</persistence-unit>
EntityManagerFactory emf = Persistence.createEntityManagerFactory("restaurants");   // once

static void inTransaction(Consumer<EntityManager> work) {
    EntityManager em = emf.createEntityManager();
    try {
        em.getTransaction().begin();
        work.accept(em);
        em.getTransaction().commit();
    } catch (RuntimeException e) {
        if (em.getTransaction().isActive()) em.getTransaction().rollback();
        throw e;
    } finally {
        em.close();
    }
}

In a Spring application, Spring creates both, and @Transactional on a service method replaces this helper (where the transaction belongs).

Entities and ids

@Entity
@Table(name = "restaurants")
public class Restaurant {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String city;

    protected Restaurant() {}                       // required by JPA; protected keeps callers out
    public Restaurant(String name, String city) { this.name = name; this.city = city; }
}
  • @Entity makes the class persistent; @Table names the table (the default is the class name).
  • Every field is a column unless marked @Transient. @Column sets the name, nullability, length and uniqueness.
  • A no-argument constructor is required, because Hibernate creates the object first and fills the fields after. It can be protected.
  • The class and its persistent methods must not be final: Hibernate subclasses entities to make lazy proxies, the same trick as the hand-written RestaurantProxy.

@GeneratedValue chooses how the id is created (entities and keys):

Strategy What it does
IDENTITY an identity column; the id is known only after the INSERT
SEQUENCE Hibernate calls a sequence first; with an allocation size of 50 it reserves 50 ids per call (hi-lo style)
UUID a UUID generated in Java
AUTO Hibernate picks one for the database

IDENTITY is the simplest. Its cost is that Hibernate must run each INSERT immediately to learn the id, so it cannot batch inserts. SEQUENCE with an allocation size lets it assign ids in memory and send inserts in batches, which matters for bulk loads.

Schema generation

With jakarta.persistence.schema-generation.database.action set to drop-and-create, Hibernate creates the tables from the annotations:

Hibernate: create table restaurants (id bigint generated by default as identity, city varchar(255) not null, name varchar(255) not null, primary key (id))
Hibernate: create table bookings (partySize integer not null, version integer not null, customer_id bigint not null, id bigint generated by default as identity, startsAt timestamp(6) not null, primary key (id))

Two things to notice: the columns are named after the Java fields (partySize, startsAt) unless @Column(name = "party_size") or a naming strategy says otherwise, and String becomes varchar(255). Generation is convenient for tests and prototypes. In production, the schema comes from versioned migration scripts (schema patterns), and Hibernate is set to validate it against the entities.

1:N and N:1

@Entity @Table(name = "restaurant_tables",
        uniqueConstraints = @UniqueConstraint(columnNames = {"restaurant_id", "number"}))
public class RestaurantTable {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "restaurant_id")
    private Restaurant restaurant;              // a reference, not an id

    private int number;
    private int seats;
}

@Entity @Table(name = "restaurants")
public class Restaurant {
    // ...
    @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL, orphanRemoval = true)
    private Set<RestaurantTable> tables = new HashSet<>();

    public void addTable(RestaurantTable t)    { tables.add(t); t.setRestaurant(this); }
    public void removeTable(RestaurantTable t) { tables.remove(t); t.setRestaurant(null); }
}

The many side holds a reference to the restaurant instead of the id. @JoinColumn names the foreign key column.

The owning side and mappedBy

The relationship now appears twice in Java (the reference and the set) but is one column in the database. JPA needs to know which of the two to read when writing that column. The side with the foreign key, @ManyToOne, is the owning side. mappedBy = "restaurant" on the other side says "this set is the inverse of the field restaurant over there; don't write anything for it".

The consequence: only changes to the owning side are saved. Adding a table to restaurant.getTables() without setting table.setRestaurant(...) writes nothing. That is why addTable sets both sides, the same rule as for two-way navigation in mapping objects to tables.

Without mappedBy, JPA treats the @OneToMany as a separate relationship and creates a join table for it, which is almost never what was intended.

Cascade

cascade = CascadeType.ALL passes persist, remove and the other operations from the restaurant to its tables. Persisting one restaurant with two tables:

Restaurant r = new Restaurant("R1", "Bologna");
r.addTable(new RestaurantTable(1, 4));
r.addTable(new RestaurantTable(2, 4));
em.persist(r);
Hibernate: insert into restaurants (city,name) values (?,?)
Hibernate: insert into restaurant_tables (number,restaurant_id,seats) values (?,?,?)
Hibernate: insert into restaurant_tables (number,restaurant_id,seats) values (?,?,?)

Hibernate orders the inserts so the parent exists before the children reference it. Cascade belongs on relationships that are composition (the parts have no life of their own), the same rule as ON DELETE CASCADE (choosing the option). Never cascade REMOVE from an order line to a menu item.

Orphan removal

orphanRemoval = true deletes a child that is removed from the collection, without calling remove on it:

Restaurant r = em.find(Restaurant.class, 1L);
r.removeTable(r.getTables().iterator().next());
Hibernate: select r1_0.id,r1_0.city,r1_0.name from restaurants r1_0 where r1_0.id=?
Hibernate: select t1_0.restaurant_id,t1_0.id,t1_0.number,t1_0.seats from restaurant_tables t1_0 where t1_0.restaurant_id=?
Hibernate: delete from restaurant_tables where id=?

Without it, the table would only lose its restaurant reference, which fails here because the column is NOT NULL.

1:1

The loyalty card shares the customer's primary key (shared primary key). @MapsId says that the id is taken from the relationship:

@Entity @Table(name = "loyalty_cards")
public class LoyaltyCard {
    @Id
    private Long customerId;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "customer_id")
    private Customer customer;

    private int points;
}

@Entity @Table(name = "customers")
public class Customer {
    // ...
    @OneToOne(mappedBy = "customer", cascade = CascadeType.ALL)
    private LoyaltyCard card;
}
Hibernate: insert into customers (email,name) values (?,?)
Hibernate: insert into loyalty_cards (points,customer_id) values (?,?)

A trap with two-way 1:1: the inverse side (Customer.card) cannot be lazy. Hibernate must know whether to put null or a proxy in the field, and the customers table has no column that says whether a card exists, so it queries. Loading a customer by email:

Hibernate: select c1_0.id,c1_0.email,c1_0.name from customers c1_0 where c1_0.email=?
Hibernate: select lc1_0.customer_id,lc1_0.points from loyalty_cards lc1_0 where lc1_0.customer_id=?

The second query runs although the code never touched the card. For a list of 100 customers, that is 100 extra queries. If the card is rarely needed, map the relationship one-way, from the card to the customer only, and look the card up when needed.

N:N

The booking navigates to its tables, one way (N:N). @JoinTable describes the join table that a mapping DAO would have handled:

@Entity @Table(name = "bookings")
public class Booking {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "customer_id")
    private Customer customer;

    @ManyToMany
    @JoinTable(name = "booking_tables",
               joinColumns = @JoinColumn(name = "booking_id"),
               inverseJoinColumns = @JoinColumn(name = "table_id"))
    private Set<RestaurantTable> tables = new HashSet<>();

    @Version
    private int version;
}
Booking b = new Booking(ada, LocalDateTime.parse("2026-12-05T20:00"), 8);
b.getTables().addAll(restaurant2.getTables());
em.persist(b);
Hibernate: insert into bookings (customer_id,partySize,startsAt,version) values (?,?,?,?)
Hibernate: insert into booking_tables (booking_id,table_id) values (?,?)
Hibernate: insert into booking_tables (booking_id,table_id) values (?,?)

The join table rows are written from the collection, in the same transaction, after the booking. To make it two-way, add @ManyToMany(mappedBy = "tables") Set<Booking> bookings on RestaurantTable, and keep both sides in step in a helper method.

Use Set, not List, for @ManyToMany. With a List (a "bag" in Hibernate's terms), removing one element makes Hibernate delete every row of the join table for that booking and insert the remaining ones again.

When the link has attributes (an order line with a quantity), @ManyToMany is the wrong tool: the join table is an entity. Map OrderLine as an @Entity with two @ManyToOne, and use @OneToMany(mappedBy = "order") from Order.

Fetch types and the N+1 problem

Every relationship has a fetch type. The defaults come from the JPA specification:

Annotation Default fetch
@OneToMany, @ManyToMany LAZY
@ManyToOne, @OneToOne EAGER

The eager defaults on the single-valued side surprise people: loading 100 tables with an eager @ManyToOne also loads their restaurants. The common advice is to write fetch = FetchType.LAZY on every @ManyToOne and @OneToOne (as above), and load what each use case needs with a query.

Lazy collections give the N+1 problem exactly as with the hand-written proxy (the N+1 problem):

List<Restaurant> rs = em.createQuery("select r from Restaurant r order by r.id", Restaurant.class).getResultList();
for (Restaurant r : rs) total += r.getTables().size();
Hibernate: select r1_0.id,r1_0.city,r1_0.name from restaurants r1_0 order by r1_0.id
Hibernate: select t1_0.restaurant_id,t1_0.id,t1_0.number,t1_0.seats from restaurant_tables t1_0 where t1_0.restaurant_id=?
Hibernate: select t1_0.restaurant_id,t1_0.id,t1_0.number,t1_0.seats from restaurant_tables t1_0 where t1_0.restaurant_id=?
Hibernate: select t1_0.restaurant_id,t1_0.id,t1_0.number,t1_0.seats from restaurant_tables t1_0 where t1_0.restaurant_id=?

Three restaurants, four queries. JOIN FETCH in JPQL (JPA's query language, which talks about entities and fields instead of tables and columns) loads the collection in the same query:

em.createQuery("select distinct r from Restaurant r left join fetch r.tables order by r.id", Restaurant.class)
Hibernate: select distinct r1_0.id,r1_0.city,r1_0.name,t1_0.restaurant_id,t1_0.id,t1_0.number,t1_0.seats from restaurants r1_0 left join restaurant_tables t1_0 on r1_0.id=t1_0.restaurant_id order by r1_0.id

One query, the same join as the hand-written findAllWithTables. Other fixes: an entity graph (@NamedEntityGraph, or a graph passed to find) that names the relationships to load for one call, and Hibernate's @BatchSize (or hibernate.default_batch_fetch_size), which loads lazy collections for many parents at once with IN.

Do not fix N+1 by making collections EAGER: every query that loads a restaurant then pays for the tables, and a JPQL query without JOIN FETCH still loads them with separate selects.

LazyInitializationException

A lazy collection can only be loaded while its EntityManager is open:

EntityManager em = emf.createEntityManager();
Restaurant r = em.find(Restaurant.class, 2L);
em.close();
r.getTables().size();
LazyInitializationException: failed to lazily initialize a collection of role: demo.Restaurant.tables: could not initialize proxy - no Session

This is the failure described for hand-written proxies (when lazy fails), made into an explicit exception. The fix is to load what the caller needs inside the transaction (JOIN FETCH, an entity graph), or return a DTO built inside the transaction. Keeping the EntityManager open for the whole web request ("open session in view") hides the exception and turns it back into N+1 queries from the view layer.

The persistence context

An EntityManager keeps a persistence context: every entity it loaded or persisted, by id. It is the identity map and unit of work from earlier pages (identity map, unit of work), and it explains most of JPA's behaviour.

One object per row. Finding the same entity twice returns the same object, and the second find sends no query:

Restaurant x = em.find(Restaurant.class, 1L);
Restaurant y = em.find(Restaurant.class, 1L);
System.out.println(x == y);
Hibernate: select r1_0.id,r1_0.city,r1_0.name from restaurants r1_0 where r1_0.id=?
same object: true

Dirty checking. There is no update method. Changing a managed entity is enough: at commit (or at a flush, when Hibernate writes pending changes before running a query), Hibernate compares each entity with the copy it took when loading it, and writes the differences.

Restaurant r = em.find(Restaurant.class, 1L);
r.setCity("Modena");
// commit
Hibernate: select r1_0.id,r1_0.city,r1_0.name from restaurants r1_0 where r1_0.id=?
Hibernate: update restaurants set city=?,name=? where id=?

An entity has one of four states:

new ──persist()──> managed ──commit / close()──> detached
                      │                             │
                  remove()                       merge()  (copies it into a managed instance)
                      v
                   removed ──commit──> row deleted

Only managed entities are tracked. Changes to a detached entity (one loaded by an EntityManager that has been closed) are ignored until it is passed to merge, which returns a managed copy. Most "my change was not saved" bugs are changes to a detached object or to the inverse side of a relationship.

The persistence context also costs memory: loading 100,000 entities in one EntityManager keeps 100,000 entities and their snapshots. Batch jobs call flush() and clear() every few hundred rows.

Optimistic locking with @Version

A @Version field turns on the version check from optimistic locking. Two users load booking 1 in separate EntityManagers; the waiter commits first, then the manager:

Hibernate: update bookings set customer_id=?,partySize=?,startsAt=?,version=? where id=? and version=?
Hibernate: update bookings set customer_id=?,partySize=?,startsAt=?,version=? where id=? and version=?
RollbackException / cause: OptimisticLockException

The SQL is the same WHERE id = ? AND version = ? written by hand earlier. Hibernate sees 0 rows updated and throws OptimisticLockException; the transaction is rolled back. Pessimistic locking is available too: em.find(Booking.class, id, LockModeType.PESSIMISTIC_WRITE) sends SELECT ... FOR UPDATE.

Inheritance

@Inheritance picks one of the three layouts from mapping objects to tables: SINGLE_TABLE (the default), JOINED or TABLE_PER_CLASS.

@Entity @Table(name = "staff")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "kind")
public abstract class Staff {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id;
    private String name;
}

@Entity @DiscriminatorValue("WAITER")
public class Waiter extends Staff { private String section; }

@Entity @DiscriminatorValue("CHEF")
public class Chef extends Staff { private String station; }
Hibernate: insert into staff (name,section,kind) values (?,?,'WAITER')
Hibernate: insert into staff (name,station,kind) values (?,?,'CHEF')
Hibernate: select s1_0.id,s1_0.kind,s1_0.name,s1_0.station,s1_0.section from staff s1_0
Waiter Gus
Chef Hal

A query on Staff returns objects of the right subclass, chosen by the discriminator. The generated table has section and station as nullable columns with no CHECK: the "a waiter must have a section" rule from the hand-written schema is lost unless a migration adds it.

Queries

  • em.find(Restaurant.class, id): by primary key; returns null if missing, and uses the persistence context first.
  • JPQL: select b from Booking b where b.customer.email = :email. Joins follow the mapped relationships, and parameters are always bound (setParameter), never concatenated.
  • getSingleResult(): one row expected; throws if there are none or several. This is the "unique result" that plain JDBC lacks.
  • Native SQL (em.createNativeQuery) for what JPQL cannot express: window functions, FOR UPDATE SKIP LOCKED, database-specific features.
  • Projections into DTOs (select new demo.RestaurantSummary(r.name, count(t)) from Restaurant r join r.tables t group by r.name) for read-only screens: no entities, no persistence context, no lazy loading.

Common mistakes

  • Setting only the inverse side (restaurant.getTables().add(t) without t.setRestaurant(restaurant)): nothing is written.
  • @OneToMany without mappedBy: an unexpected join table.
  • Leaving @ManyToOne eager, so loading a list loads every parent.
  • EAGER collections to avoid LazyInitializationException, instead of fetching what the use case needs.
  • cascade = ALL on associations that are not composition, so deleting an item deletes orders.
  • equals/hashCode on the generated id in entities kept in Sets before they are persisted (identity and equality).
  • drop-and-create or update schema generation in production. Use migrations, and validate.
  • Calling em.merge or save on already managed entities "to be sure". It does nothing useful and hides misunderstandings about the persistence context.