JAVA-250 · Lesson 7 of 12 · 27 min

Object-relational mapping and JPA

▶ Video coming soon A video version of this lesson is on the way.

Two weeks after the DAO session, on Friday, November 5, Ingrid brought a printout from ShopBook, the booking system Hamza had built for the rental fleet. Its BookingDao had grown to nine hundred lines. Most of them did the same three jobs again and again: copy columns into fields, copy fields back into columns, and remember which objects had changed so that they could be saved. "That work is so regular that a library can do it," she said. That library is an object-relational mapper (ORM), and the standard Java interface to one is the Jakarta Persistence API, still usually called JPA. This lesson explains what problem an ORM solves, what JPA and Hibernate are, and the two ideas at the heart of every JPA program: the persistence context and the life cycle of an entity.

Objects and tables do not fit exactly

Java programs model the world as objects that point at each other: a Booking holds a reference to its Bike, and a Bike holds a list of its Bookings. Relational databases model it as tables of rows that refer to each other by key values: a booking row holds the tag of its bike. The two models agree on a great deal, which is why mapping between them works at all, but they differ in ways that are known together as the object-relational impedance mismatch. The table below lists the main differences, each of which an ORM has to bridge.

The object-relational impedance mismatch.
QuestionIn JavaIn a relational database
How is one thing found?By following a referenceBy a key value in a WHERE clause
What makes two things the same?Identity (==) or equalsThe same primary key
How are relationships stored?References and collections, in both directions if wantedA foreign key on one side only
Many-to-many?A collection on each sideA separate join table
Inheritance?extendsNo direct equivalent; several mapping strategies
How is change saved?Assign a fieldAn UPDATE statement
How much is loaded?Whatever the reference graph reachesExactly what the query selects

The example below shows the mismatch in a small way. The rows are what the database holds; turning them into objects that point at each other takes a lookup by key, and turning one changed object back into SQL needs someone to notice the change and write the statement. A DAO writes that code by hand for every table. An ORM writes it from a description of the mapping.

Java Example · Main.java
import java.util.*;

public class Main {
    record BikeRow(String tag, String kind) {}
    record BookingRow(int id, String bikeTag, String customer) {}

    static class Bike {
        final String tag; final String kind;
        final List<Booking> bookings = new ArrayList<>();
        Bike(String tag, String kind) { this.tag = tag; this.kind = kind; }
    }
    static class Booking {
        final int id; final Bike bike; final String customer;
        Booking(int id, Bike bike, String customer) { this.id = id; this.bike = bike; this.customer = customer; }
    }

    public static void main(String[] args) {
        List<BikeRow> bikeRows = List.of(new BikeRow("SG-0007-AR", "CARGO"), new BikeRow("SG-0003-CI", "CITY"));
        List<BookingRow> bookingRows = List.of(new BookingRow(1, "SG-0007-AR", "Ravi"),
                new BookingRow(3, "SG-0003-CI", "Mei"), new BookingRow(4, "SG-0007-AR", "Ana"));

        // rows to objects: keys become references, in both directions
        Map<String, Bike> bikes = new TreeMap<>();
        for (BikeRow r : bikeRows) bikes.put(r.tag(), new Bike(r.tag(), r.kind()));
        for (BookingRow r : bookingRows) {
            Bike bike = bikes.get(r.bikeTag());
            bike.bookings.add(new Booking(r.id(), bike, r.customer()));
        }

        for (Bike b : bikes.values()) {
            System.out.println(b.tag + " (" + b.kind + "): " + b.bookings.stream().map(k -> k.customer).toList());
        }
        Booking ana = bikes.get("SG-0007-AR").bookings.get(1);
        System.out.println("Ana's booking is for a " + ana.bike.kind + " bike");

        // objects back to rows: only the foreign key value survives
        System.out.println("Saved as: " + new BookingRow(ana.id, ana.bike.tag, ana.customer));
    }
}
Output
SG-0003-CI (CITY): [Mei]
SG-0007-AR (CARGO): [Ravi, Ana]
Ana's booking is for a CARGO bike
Saved as: BookingRow[id=4, bikeTag=SG-0007-AR, customer=Ana]

What this code does

The bike tag in each booking row is turned into a reference by looking it up in a map, and the booking is also added to its bike's list, so the relationship can be followed both ways in Java. Going back, the reference shrinks to its key value, which is all a row can store. Every DAO repeats code like this for each table, which is the work an ORM takes over.

JPA, Jakarta Persistence and Hibernate

JPA is a specification: a set of interfaces, annotations and rules, with no implementation of its own. It began in 2006 as the Java Persistence API, part of Java EE. When Oracle gave Java EE to the Eclipse Foundation, the platform was renamed Jakarta EE and the specification became Jakarta Persistence, and from version 3.0 its packages moved from javax.persistence to jakarta.persistence. The current version is Jakarta Persistence 3.2. Older tutorials and Stack Overflow answers use the javax names, which no longer work with current libraries.

An implementation of the specification, called a persistence provider, does the actual work. Hibernate ORM is the most widely used; others include EclipseLink, the reference implementation. Hibernate 7, released in 2025, implements Jakarta Persistence 3.2 and requires Java 17 or later; the 7.x series is current in November 2026. Spring Boot's spring-boot-starter-data-jpa uses Hibernate by default, so most Spring applications that talk to a database through JPA are running Hibernate underneath. Hibernate also has its own native API and features beyond the specification, but code that uses only jakarta.persistence types can in principle switch providers.

build.gradle.kts (excerpt)
dependencies {
    implementation("org.hibernate.orm:hibernate-core:7.4.0.Final")   // brings jakarta.persistence-api 3.2
    runtimeOnly("org.postgresql:postgresql:42.7.13")
    runtimeOnly("com.zaxxer:HikariCP:7.0.2")
}

What this code does

Hibernate's core library pulls in the Jakarta Persistence interfaces, so application code compiles against jakarta.persistence. The JDBC driver and the pool are still needed, because Hibernate sends its SQL through JDBC like any other Java program. Check the Hibernate releases page for the newest 7.x patch before copying the version.

Entities and the EntityManager

An entity is a class whose objects are stored as rows. It is marked with @Entity, has a field marked @Id for the primary key, and needs a constructor with no arguments that JPA can call. Fields become columns by default, using the field name; @Table and @Column change the names when they differ, as they usually do, because Java uses camelCase and SQL uses snake_case. Lesson 8 covers keys and relationships in detail.

Java Example · Part.java (needs Jakarta Persistence)
import jakarta.persistence.*;

@Entity
@Table(name = "part")
public class Part {
    @Id
    private String code;

    private String name;
    private String shelf;
    private int quantity;

    @Column(name = "reorder_at")
    private int reorderAt;

    @Column(name = "pack_size")
    private int packSize;

    protected Part() {}                      // for JPA

    public Part(String code, String name, String shelf, int quantity, int reorderAt, int packSize) {
        this.code = code; this.name = name; this.shelf = shelf;
        this.quantity = quantity; this.reorderAt = reorderAt; this.packSize = packSize;
    }

    public String getCode() { return code; }
    public int getQuantity() { return quantity; }
    public void receive(int count) { quantity += count; }
    public boolean isLow() { return quantity < reorderAt; }
}

What this code does

Records cannot be entities, because JPA needs to create an empty object and then set its fields, and it needs to change fields later; that is why Part is an ordinary class with a protected no-argument constructor. The annotations describe the mapping and contain no SQL. Methods such as receive express the business rule on the object itself, and saving the change is JPA's job.

A program talks to JPA through an EntityManager. It is created by an EntityManagerFactory, which is expensive to build, because it reads all the mappings and sets up the connection pool, and so is created once when the program starts. EntityManagers are cheap and short-lived: typically one per request or unit of work, used inside one transaction and then closed. The main operations are find to load by key, persist to make a new object stored, remove to delete, createQuery for JPQL queries (lesson 9) and the transaction methods.

Java Example · Receiving tubes with JPA (needs Hibernate and a driver)
EntityManagerFactory emf = Persistence.createEntityManagerFactory("stockstore");   // once, at startup

try (EntityManager em = emf.createEntityManager()) {
    em.getTransaction().begin();

    Part tubes = em.find(Part.class, "TUBE-700x25");       // SELECT ... FROM part WHERE code = ?
    tubes.receive(20);                                       // no SQL yet

    em.persist(new Part("VALVE-PR", "Presta valve core", "A-04", 30, 10, 10));

    em.getTransaction().commit();                           // UPDATE part ... ; INSERT INTO part ...
}

What this code does

Nothing in this code says UPDATE: the program changes the tubes object, and at commit Hibernate notices the change and writes it. The new valve part is inserted at commit too. Since Jakarta Persistence 3.1, EntityManager is AutoCloseable, so try-with-resources closes it.

Representative log with show_sql enabled
Hibernate: select p1_0.code,p1_0.name,p1_0.pack_size,p1_0.quantity,p1_0.reorder_at,p1_0.shelf from part p1_0 where p1_0.code=?
Hibernate: insert into part (name,pack_size,quantity,reorder_at,shelf,code) values (?,?,?,?,?,?)
Hibernate: update part set name=?,pack_size=?,quantity=?,reorder_at=?,shelf=? where code=?

What this code does

With hibernate.show_sql turned on, Hibernate logs each statement it sends. This is representative output: the aliases such as p1_0 come from Hibernate 6 and later, and Hibernate orders inserts before updates when it flushes. The values are bound as parameters, exactly like the prepared statements of lesson 3.

The persistence context

Each EntityManager owns a persistence context: a set of the entity objects it has loaded or persisted, with at most one object for each primary key. It is sometimes called the first-level cache. It gives two guarantees that explain almost everything JPA does. The first is the identity guarantee: within one persistence context, finding the same key twice returns the same Java object, not a copy, so == is true and a change made through one reference is visible through the other. The second is automatic dirty checking: when an entity is loaded, the provider keeps a snapshot of its state, and when the context is flushed, normally just before commit, it compares every managed entity with its snapshot and writes an UPDATE for each one that changed.

An EntityManager box containing a persistence context. Inside, a table with two columns: key and entity object, holding TUBE-700x25 and BELL, each with a snapshot beside it. Arrows show find returning the existing object, and flush comparing objects with snapshots and sending UPDATE to the database.
A persistence context maps each key to one object and keeps a snapshot of its loaded state for dirty checking.

The example below is a toy persistence context written with the standard library. It stores loaded objects in an identity map, keeps snapshots as copies of the loaded values, and at flush prints the UPDATE that a provider would send. Real providers do the same in far more detail.

Java Example · Main.java
import java.util.*;

public class Main {
    static class Part {
        final String code; int quantity; String shelf;
        Part(String code, int quantity, String shelf) { this.code = code; this.quantity = quantity; this.shelf = shelf; }
    }

    // pretend database: code -> {quantity, shelf}
    static final Map<String, Object[]> TABLE = new TreeMap<>(Map.of(
            "TUBE-700x25", new Object[]{14, "A-02"}, "BELL", new Object[]{3, "C-03"}, "GRIPS", new Object[]{9, "C-03"}));
    static int selects = 0;

    static class PersistenceContext {
        private final Map<String, Part> identityMap = new LinkedHashMap<>();
        private final Map<String, Object[]> snapshots = new HashMap<>();

        Part find(String code) {
            Part p = identityMap.get(code);
            if (p != null) return p;                                  // already managed: no SELECT
            selects++;
            Object[] row = TABLE.get(code);
            p = new Part(code, (Integer) row[0], (String) row[1]);
            identityMap.put(code, p);
            snapshots.put(code, new Object[]{p.quantity, p.shelf});
            return p;
        }

        void flush() {
            for (Part p : identityMap.values()) {
                Object[] old = snapshots.get(p.code);
                List<String> changed = new ArrayList<>();
                if (p.quantity != (Integer) old[0]) changed.add("quantity=" + p.quantity);
                if (!p.shelf.equals(old[1])) changed.add("shelf='" + p.shelf + "'");
                if (changed.isEmpty()) continue;
                System.out.println("UPDATE part SET " + String.join(", ", changed) + " WHERE code='" + p.code + "'");
                TABLE.put(p.code, new Object[]{p.quantity, p.shelf});
                snapshots.put(p.code, new Object[]{p.quantity, p.shelf});
            }
        }
    }

    public static void main(String[] args) {
        PersistenceContext pc = new PersistenceContext();
        Part a = pc.find("TUBE-700x25");
        Part b = pc.find("TUBE-700x25");
        System.out.println("Same object: " + (a == b) + ", SELECTs: " + selects);

        a.quantity += 20;                        // receive a delivery
        System.out.println("Seen through b: " + b.quantity);
        Part bell = pc.find("BELL");
        bell.shelf = "C-04";
        pc.find("GRIPS");                        // loaded but not changed

        pc.flush();
        System.out.println("Second flush:");
        pc.flush();
        System.out.println("SELECTs in total: " + selects);
    }
}
Output
Same object: true, SELECTs: 1
Seen through b: 34
UPDATE part SET quantity=34 WHERE code='TUBE-700x25'
UPDATE part SET shelf='C-04' WHERE code='BELL'
Second flush:
SELECTs in total: 3

What this code does

The second find for the tubes returns the object already in the identity map, so == is true, only one SELECT is counted and the change made through a is visible through b. At flush the tubes and the bell differ from their snapshots and produce updates, while the grips produce nothing. After a flush the snapshots are refreshed, so a second flush finds nothing to write; unlike this toy, Hibernate by default writes every column of a changed entity unless the class is marked @DynamicUpdate.

Two consequences follow. A persistence context is a unit of work, not a cache to keep for the life of the program: it grows with every entity loaded, and its objects drift out of date as other users change the database. And because writes happen at flush, not when a field is assigned, a JPA program can change several entities and have all the updates sent together at commit, inside one transaction. Hibernate, by default, also orders and batches them where it can.

The life cycle of an entity

An entity object is always in one of four states with respect to a persistence context. A new (or transient) object has just been created with new and JPA knows nothing about it. A managed object belongs to a persistence context: changes to it will be written at flush. A detached object was managed, but its context has been closed or cleared, so changes to it are no longer tracked. A removed object is managed but scheduled for deletion at flush. The operations of the EntityManager move objects between these states.

A state diagram with four states: New, Managed, Detached and Removed. Arrows: new to managed labeled persist; database to managed labeled find or query; managed to detached labeled close, clear or detach; detached to managed labeled merge (returns a managed copy); managed to removed labeled remove; removed to managed labeled persist; removed to database deletion labeled flush.
Entity states and the operations that move between them.
EntityManager operations and entity states.
OperationFromToNote
persist(e)newmanagedINSERT at flush (or at once, for IDENTITY keys)
find, queriesdatabasemanagedReturns the object in the context if already there
remove(e)managedremovedDELETE at flush
detach(e), clear(), close()manageddetachedChanges are no longer tracked
merge(e)detached or newmanaged copyCopies state onto a managed object and returns it
flush(), commitmanaged or removeddatabaseWrites inserts, updates and deletes

The detached state catches many beginners. A web request loads a Part, the EntityManager closes at the end of the request, and the next request changes the same Java object and expects it to be saved. Nothing happens, because no context is watching it. merge solves this, but it does not attach the object you pass: it copies its state onto a managed instance, loading one if necessary, and returns that instance. Code that keeps using the old reference after merge is changing a detached object again. The simulation below records the state transitions and shows that trap.

Java Example · Main.java
import java.util.*;

public class Main {
    enum State { NEW, MANAGED, DETACHED, REMOVED }

    static class Part {
        final String code; int quantity; State state = State.NEW;
        Part(String code, int quantity) { this.code = code; this.quantity = quantity; }
        public String toString() { return code + "(" + quantity + ", " + state + ")"; }
    }

    static class EntityManager {
        final Map<String, Part> context = new TreeMap<>();
        final Map<String, Integer> database;
        EntityManager(Map<String, Integer> database) { this.database = database; }

        void persist(Part p) { p.state = State.MANAGED; context.put(p.code, p); }
        Part merge(Part detached) {
            Part managed = context.get(detached.code);
            if (managed == null) {
                managed = new Part(detached.code, database.getOrDefault(detached.code, 0));
                managed.state = State.MANAGED;
                context.put(managed.code, managed);
            }
            managed.quantity = detached.quantity;       // copy the state across
            return managed;                              // the argument stays detached
        }
        void flush() { context.values().forEach(p -> database.put(p.code, p.quantity)); }
        void close() { context.values().forEach(p -> p.state = State.DETACHED); context.clear(); }
    }

    public static void main(String[] args) {
        Map<String, Integer> db = new TreeMap<>();

        EntityManager em1 = new EntityManager(db);
        Part bell = new Part("BELL", 3);
        System.out.println("created: " + bell);
        em1.persist(bell);
        System.out.println("persisted: " + bell);
        em1.flush();
        em1.close();
        System.out.println("after close: " + bell);

        bell.quantity = 9;                               // change while detached
        System.out.println("database after detached change: " + db);

        EntityManager em2 = new EntityManager(db);
        Part managed = em2.merge(bell);
        managed.quantity -= 2;                           // sell 2 through the managed copy
        bell.quantity = 100;                             // the old reference is still detached
        em2.flush();
        System.out.println("merge returned a different object: " + (managed != bell));
        System.out.println(managed + " / " + bell);
        System.out.println("database: " + db);
    }
}
Output
created: BELL(3, NEW)
persisted: BELL(3, MANAGED)
after close: BELL(3, DETACHED)
database after detached change: {BELL=3}
merge returned a different object: true
BELL(7, MANAGED) / BELL(100, DETACHED)
database: {BELL=7}

What this code does

The bell is managed after persist and detached after close, so setting its quantity to 9 changes nothing in the database. merge copies the 9 onto a new managed object and returns it; the sale through that object is saved, while the later change through the old reference is lost. The database ends with 7 bells, the value of the managed copy.

Configuring a persistence unit

JPA needs to know which entity classes exist, which database to use and which provider settings apply. Together these form a persistence unit, traditionally described in META-INF/persistence.xml and given a name, here stockstore, that the program passes to createEntityManagerFactory. Jakarta Persistence 3.2 also adds PersistenceConfiguration, which builds the same unit in Java code, and Spring Boot builds it from application properties instead, so many projects never write the XML file at all.

META-INF/persistence.xml
<persistence xmlns="https://jakarta.ee/xml/ns/persistence" version="3.2">
  <persistence-unit name="stockstore" transaction-type="RESOURCE_LOCAL">
    <class>ca.secondgear.stockstore.Part</class>
    <class>ca.secondgear.stockstore.StockMovement</class>
    <properties>
      <property name="jakarta.persistence.jdbc.url" value="jdbc:h2:mem:stockstore-trial"/>
      <property name="jakarta.persistence.jdbc.user" value="sa"/>
      <property name="jakarta.persistence.schema-generation.database.action" value="none"/>
      <property name="hibernate.show_sql" value="true"/>
    </properties>
  </persistence-unit>
</persistence>

What this code does

RESOURCE_LOCAL means the program manages transactions itself through EntityTransaction, as in the earlier listing; in an application server or with Spring, transactions are usually managed for you. Hamza's trial used an in-memory H2 database, so no real data was at risk. Schema generation is turned off because the schema belongs to Flyway migrations, the subject of lesson 11. Letting Hibernate create or update tables is handy for experiments but unsafe for real data.

Is JPA the right tool? It shines when a program works with a rich graph of objects, loads them, changes them through business methods and saves them, as ShopBook does with bikes, bookings and customers. It is less useful for reporting and bulk work, where SQL is already the clearest description, and it adds a layer to learn: the persistence context, the states and lazy loading (lesson 10) all have to be understood to avoid surprises. Many teams use both, JPA for the object model and plain SQL for reports. Ingrid's rule for the shop was simple: use JPA where the program changes objects, and SQL where it asks questions.

Try it yourself

Count the SELECTs

Complete find so that it returns the object already in cache if there is one, and otherwise increments selects, creates the part, stores it in cache and returns it.

The program finds three parts, two of them twice, and prints SELECTs: 3 and Same: true.

import java.util.*;

public class Main {
    record Part(String code) {}
    static int selects = 0;
    static final Map<String, Part> cache = new HashMap<>();

    static Part find(String code) {
        selects++;
        return new Part(code);
    }

    public static void main(String[] args) {
        Part a = find("BELL");
        find("GRIPS");
        find("CHAIN-11");
        find("GRIPS");
        Part b = find("BELL");
        System.out.println("SELECTs: " + selects);
        System.out.println("Same: " + (a == b));
    }
}

Try it yourself

Find the dirty fields

Write changes(int[] snapshot, int[] current) returning the names from FIELDS whose values differ, in order.

The program prints [quantity, reorderAt] and then [].

import java.util.*;

public class Main {
    static final String[] FIELDS = {"quantity", "reorderAt", "packSize"};

    static List<String> changes(int[] snapshot, int[] current) {
        return List.of();
    }

    public static void main(String[] args) {
        System.out.println(changes(new int[]{14, 10, 10}, new int[]{34, 12, 10}));
        System.out.println(changes(new int[]{3, 4, 6}, new int[]{3, 4, 6}));
    }
}

Common mistakes

  • MistakeImporting javax.persistence with Hibernate 6 or 7.

    InsteadUse jakarta.persistence; the javax names belong to JPA 2.x and older providers.

  • MistakeCalling an UPDATE method after changing a managed entity.

    InsteadThere is none to call: dirty checking writes the change at flush.

  • MistakeChanging a detached object and expecting it to be saved.

    InsteadLoad it in the current context, or use the object that merge returns.

  • MistakeKeeping one EntityManager for the life of the program.

    InsteadUse one per unit of work and close it; create the factory once.

  • MistakeLetting Hibernate create or update the production schema.

    InsteadManage the schema with migrations and set schema generation to none.

Summary and key terms

  • Objects and tables model data differently: references against keys, identity against primary keys, two-way collections against one foreign key, and field assignment against UPDATE.
  • An object-relational mapper bridges these differences from a description of the mapping.
  • JPA, now Jakarta Persistence 3.2 in the jakarta.persistence packages, is the standard specification, and Hibernate ORM 7 is its most widely used implementation.
  • An entity is a class marked @Entity with an @Id and a no-argument constructor; @Table and @Column adjust names.
  • An EntityManagerFactory is built once; an EntityManager is used for one unit of work.
  • Its persistence context holds one object per key and snapshots of loaded state, so finding a key twice returns the same object and changed entities are written automatically at flush.
  • Entities are new, managed, detached or removed, and persist, find, remove, detach, merge and flush move them between states; merge returns a managed copy.
  • A persistence unit, in persistence.xml or code, names the entities, the database and the settings.
Object-relational mapper
A library that converts between objects and rows from a description of the mapping.
Impedance mismatch
The set of differences between the object model and the relational model.
Jakarta Persistence
The standard Java specification for object-relational mapping, formerly the Java Persistence API.
Persistence provider
An implementation of Jakarta Persistence, such as Hibernate ORM or EclipseLink.
Entity
A class whose objects are stored as rows, marked with @Entity.
EntityManager
The interface a program uses to find, persist, remove and query entities.
Persistence context
The set of managed entities of one EntityManager, with one object per key.
Dirty checking
Comparing managed entities with their loaded snapshots to find changes to write.
Flush
Sending the pending inserts, updates and deletes of a persistence context to the database.
Detached
The state of an entity that was managed but whose context has been closed or cleared.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Why can't a Java record be a JPA entity?

    Show answer

    JPA must create an empty object with a no-argument constructor and set and change its fields, which records do not allow.

  2. What does em.find return if the same key was found earlier in the same EntityManager?

    Show answer

    The same object, without another SELECT.

  3. When is the UPDATE for a changed managed entity sent?

    Show answer

    At flush, normally just before commit.

  4. What does merge return?

    Show answer

    A managed instance with the detached object's state copied onto it.

  5. Which package do current JPA annotations come from?

    Show answer

    jakarta.persistence.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz