Skip to content
Tutorials Center
My learning

Topics

Lesson 48 of 119 ยท JPA and Hibernate

ORM and JPA Introduction

Understand object-relational mapping - the object-relational mismatch, what an ORM does for you, JPA vs Hibernate, EntityManager basics and when plain JDBC is the better choice.

In the JDBC lessons you wrote every SQL statement by hand and copied every column into a Java object yourself. That works, and for some code it is the best approach. But in a typical business application, most of that code is the same pattern repeated for fifty tables: INSERT with ten placeholders, SELECT and ten rs.getXxx calls, UPDATE with the same ten columns again. Worse, objects and tables don't fit together as neatly as those patterns suggest.

An ORM (object-relational mapper) automates the translation between objects and rows. In Java, the standard for ORMs is Jakarta Persistence, better known as JPA, and its most popular implementation is Hibernate. This lesson explains the problem an ORM solves, what an ORM actually does at run time, how JPA and Hibernate relate, and when you should not use one. Hibernate can't run in this sandbox, so the JPA code is read-only, but every runnable example builds the same mechanics by hand on H2 so you can see what happens inside. The JDBC CRUD lesson and The DAO and Repository Patterns are the background for this chapter.

The object-relational mismatch

Objects and relational tables are both ways to model data, but they were designed with different goals. The differences are known as the object-relational impedance mismatch:

Topic In Java In the database
Identity two references are the same object if a == b; equal if a.equals(b) two rows are the same if their primary keys are equal
Associations a Book holds a reference to its Author; an Author can hold a List<Book> a book row holds an author_id foreign key; the "list of books" is a query
Direction references point one way; both directions need two fields a foreign key can be joined from either side
Many-to-many each side holds a collection needs a third join table
Granularity a Customer has an Address object the address is usually a few columns in the customer table
Inheritance Card extends Payment tables have no inheritance
Navigation walk the graph: order.getCustomer().getAddress().getCity() fetch what you need with joins, ideally in one query
Types enums, LocalDate, BigDecimal, boolean VARCHAR, DATE, DECIMAL, sometimes no boolean type at all

None of these is a problem you can't solve with JDBC. The trouble is that you solve them again in every DAO, slightly differently each time. The first program shows two of them in plain JDBC: mapping a foreign key back into an object reference, and the identity problem that appears when the same row is loaded twice.

Java Mapping a join by hand, and the identity problem

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 join became an object reference, but only because the mapping code built one. And because each row created its own Author, the program now holds two objects for one database row. Change one and the other is stale; save both and the last one wins. To avoid this, the mapping code would need a cache of already-loaded authors per unit of work. That cache is one of the main things an ORM provides.

What an ORM does

An ORM like Hibernate does five big jobs, all driven by mapping metadata (annotations or XML) that describe which class goes to which table:

  1. SQL generation. From the mapping, it writes the INSERT, UPDATE, DELETE and SELECT statements, including joins for associations, using the right SQL dialect for your database.
  2. Row โ†” object conversion. It reads ResultSets into objects and objects into parameters, converting types (enums, java.time, BigDecimal, embedded objects).
  3. Identity map (the persistence context). Within one unit of work, each row is represented by exactly one object. Loading the same author twice returns the same instance.
  4. Change tracking (dirty checking). It remembers what each loaded object looked like and, at commit, writes UPDATEs only for objects that changed. You don't call save after modifying a managed object.
  5. Lazy loading. Associations such as author.getBooks() can be loaded only when first used, instead of pulling the whole object graph at once.

The second program builds a miniature version of job 1 and 2: it reads the record components of a class with reflection and generates the CREATE TABLE, INSERT and SELECT statements, then runs them on H2. A real ORM does the same thing with far more care (and with annotations instead of naming conventions).

Java A tiny ORM that writes the SQL for you

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.

Not one line of that program mentions a specific column, yet it created the table, inserted rows and read one back into a typed object. Add a field to Product and every statement follows. That is the core value of an ORM: the mapping is declared once, and the repetitive SQL disappears from your code.

JPA, Hibernate and friends

Several names are involved, and they are often used loosely:

Name What it is
JPA / Jakarta Persistence a specification: the jakarta.persistence annotations (@Entity, @Id, ...) and interfaces (EntityManager, Query, ...). Version 3.2 is part of Jakarta EE 11. It was called Java Persistence API in the javax.persistence era.
Hibernate ORM the most widely used implementation of JPA (version 7 implements Jakarta Persistence 3.2). It also has its own native API (Session, SessionFactory) and many extra features.
EclipseLink another JPA implementation, the reference implementation of the specification.
Spring Data JPA a layer on top of JPA that generates repository classes from interfaces (interface BookRepository extends JpaRepository<Book, Long>). It uses Hibernate underneath by default.

You program against the JPA interfaces and annotations, and Hibernate does the work. That keeps most of your code portable, while you can still use Hibernate-specific features when you need them. Spring Data JPA, covered in its own lesson, removes even more boilerplate, but everything it does turns into JPA calls, so understanding JPA comes first.

A first look at JPA code

Here is the library from the first example written with JPA. The class is an entity: a class whose instances are stored in a table. The annotations are the mapping metadata.

Java
import jakarta.persistence.*;

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

    private String name;

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

    protected Author() { }                 // JPA needs a no-argument constructor
    public Author(String name) { this.name = name; }

    public Long getId() { return id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public List<Book> getBooks() { return books; }
}

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

    private String title;

    @ManyToOne(fetch = FetchType.LAZY)
    private Author author;                 // an object reference; Hibernate manages author_id

    protected Book() { }
    public Book(String title, Author author) { this.title = title; this.author = author; }
    // getters ...
}

You work with entities through an EntityManager, which you get from an EntityManagerFactory built once per application (the next lesson shows the setup):

Java
EntityManagerFactory emf = Persistence.createEntityManagerFactory("library");

EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
    Author leGuin = new Author("Ursula K. Le Guin");
    em.persist(leGuin);                                     // INSERT INTO author ...
    em.persist(new Book("A Wizard of Earthsea", leGuin));   // INSERT INTO book ... author_id
    em.persist(new Book("The Dispossessed", leGuin));

    Author found = em.find(Author.class, leGuin.getId());   // no SQL: already in the persistence context
    found.setName("Ursula Le Guin");                        // no save call: dirty checking finds it

    List<Book> books = em.createQuery(
            "SELECT b FROM Book b WHERE b.author.name LIKE :name", Book.class)
        .setParameter("name", "Ursula%")
        .getResultList();                                   // JPQL: queries entities, not tables

    tx.commit();                                            // flush: UPDATE author SET name = ...
} catch (RuntimeException e) {
    if (tx.isActive()) tx.rollback();
    throw e;
} finally {
    em.close();
}

The important operations:

Method Effect
persist(entity) make a new object managed; it is inserted at the next flush (or immediately, for identity columns)
find(Type.class, id) load by primary key; returns the managed instance from the context if present, null if no row
merge(entity) copy the state of a detached object into a managed one and return it
remove(entity) schedule a managed entity for deletion
createQuery(jpql, Type.class) run a JPQL query (Querying with JPQL and the Criteria API)
flush() write pending changes to the database now, without committing

In Spring applications you don't write the begin/commit/rollback block yourself; @Transactional wraps the method in exactly that pattern (Entity Lifecycle and Transactions).

The persistence context: identity map and dirty checking

The comments in that code hide the most important idea in JPA. Every EntityManager has a persistence context: a map from (entity type, primary key) to the one managed instance for that row. It guarantees that within one EntityManager, em.find(Author.class, 1L) == em.find(Author.class, 1L). That solves the identity problem from the first example.

When the context loads an entity, it also keeps a snapshot of its field values. At flush time it compares each managed entity with its snapshot and generates an UPDATE for every difference. So modifying a managed object is saving it; there is no update() method to forget.

The program below implements a small persistence context over JDBC to show both behaviors. Watch the SQL log: which calls hit the database, and which are answered from memory.

Java A persistence context with dirty checking

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 find(1) came from memory and returned the very same object. At commit, the context found one changed field on one entity and wrote a single, narrow UPDATE; the untouched author produced no SQL at all. (Hibernate updates all columns of a changed entity by default, which lets it reuse one prepared statement; @DynamicUpdate switches to changed-columns-only like this demo.)

This behavior is powerful and occasionally surprising. Code that modifies an entity "just to format it for display" inside a transaction will write that change to the database. The rule is simple once you know it: a managed entity is a live view of its row until the persistence context is closed.

Lazy loading

When you load an Author, should Hibernate also load all their books? And each book's reviews? Loading the whole graph would be slow; loading nothing would make author.getBooks() useless. JPA's answer is lazy loading: the collection is a placeholder that runs its query on first access.

Java
Author author = em.find(Author.class, 1L);   // SELECT ... FROM author WHERE id = 1
List<Book> books = author.getBooks();         // no SQL yet: an uninitialized collection
int count = books.size();                     // NOW: SELECT ... FROM book WHERE author_id = 1

The program below imitates such a collection with a Supplier: it counts the queries it runs, and you can see that nothing happens until the list is actually used.

Java A lazy collection that loads on first use

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.

Listing the names cost one query, because no collection was touched. Asking for Butler's books triggered exactly one more. But the loop at the end shows the dark side: printing a count for each author ran one extra query per author that hadn't been loaded yet. With 3 authors that's harmless; with 500 authors on a web page it is 501 queries. This is the infamous N+1 problem, and avoiding it (with join fetches, entity graphs and batch fetching) is one of the most important ORM skills; it gets a full lesson in Fetching Strategies and the N+1 Problem.

When not to use an ORM

An ORM shines for transactional business logic: load a few entities, change them according to rules, commit. It is a poor fit when:

  • Reporting and analytics need aggregates, window functions and complex joins over many rows. Write SQL (or use jOOQ) and map results to records.
  • Bulk operations touch thousands or millions of rows. UPDATE product SET price = price * 1.1 WHERE category = ? is one statement; loading every entity to change it is thousands of statements and a lot of memory.
  • The schema is not yours, for example a legacy database with odd keys and stored procedures. MyBatis (SQL in mapping files) or plain JDBC may be simpler.
  • You don't want the magic. Lazy loading, dirty checking and flush timing are invisible by design. Teams that dislike that choose Spring's JdbcClient, jOOQ or plain JDBC with records.

Most real applications mix both: JPA for the domain model and day-to-day CRUD, and hand-written SQL (through JPA native queries or a JDBC template) for the handful of heavy queries. Whatever you choose, turn on SQL logging during development and read what your ORM actually sends. An ORM saves you from writing SQL, never from understanding it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Plain JDBC code loads two books by the same author and builds an Author object for each row. What is true?

    Each row creates its own object. An ORM's persistence context fixes this by returning one managed instance per row within a unit of work.
  2. 2. How do JPA and Hibernate relate?

    You code against jakarta.persistence types; Hibernate (or EclipseLink) provides the implementation at run time.
  3. 3. Inside a transaction, you call em.find(Product.class, 7L) and then product.setPrice(25). You never call persist or merge. What happens at commit?

    Entities loaded by an EntityManager are managed. Dirty checking at flush time writes their changes automatically.
  4. 4. A page lists 200 authors and shows each one's number of books, using a lazy books collection. How many queries run?

    One query loads the authors, then each lazy collection runs its own query on first access. This is the N+1 problem.
  5. 5. Which task is usually a poor fit for loading and modifying JPA entities?

    Bulk changes are best done with a single SQL UPDATE. Loading millions of entities to modify them one by one wastes memory and creates millions of statements.

Summary

  • Objects and tables model data differently: identity, associations, granularity, inheritance, navigation and types don't line up. This is the object-relational mismatch.
  • An ORM maps classes to tables from metadata and then generates SQL, converts rows to objects, keeps one instance per row (identity map), writes changes automatically (dirty checking) and loads associations on demand (lazy loading).
  • JPA (Jakarta Persistence) is the standard API; Hibernate is its most popular implementation; Spring Data JPA builds repositories on top.
  • You use entities through an EntityManager: persist, find, merge, remove, JPQL queries and flush, inside transactions.
  • A managed entity is a live view of its row: changes are saved at commit without any save call.
  • Lazy loading makes graphs cheap to load but can cause the N+1 problem.
  • Use plain SQL for reports, bulk updates and odd schemas; always look at the SQL your ORM generates.

Next: Entities and Hibernate Setup configures Hibernate and maps your first entities with @Entity, @Id, @Table and @Column.