Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท Getting Started

CRUD with Hibernate

Create, read, update and delete entities with Hibernate Session methods persist, find, merge and remove, see automatic updates, and learn the SQL behind each operation.

CRUD, create, read, update and delete, is the heart of any data-driven application. With Hibernate each operation is one method call on a Session inside a transaction. The interesting part is not the call itself but what happens behind it: when the SQL runs, why an update often needs no call at all, and why the identifier matters.

This lesson shows the real Hibernate code for each operation (read-only here) and the SQL it produces, and then lets you run a stand-in repository that does the same four operations with plain JDBC so you can watch the statements.

The four operations

Assume the Book entity from the first project, with a generated id, a title and pages.

Create: persist

Java
sessionFactory.inTransaction(session -> {
    Book book = new Book("Refactoring", 448);
    session.persist(book);                 // schedules an INSERT
    System.out.println(book.getId());      // id is already assigned for IDENTITY/SEQUENCE ids
});

persist makes a new object managed: the session now tracks it and will insert it. The INSERT is sent at flush time, usually at commit, unless the ID strategy needs the database to produce the key (identity columns), in which case the insert happens immediately. More in ID generation.

Read: find and queries

Java
sessionFactory.inSession(session -> {
    Book book = session.find(Book.class, 1L);          // SELECT ... WHERE id = ?  (null if missing)
    Book ref  = session.getReference(Book.class, 1L);  // proxy, SELECT only when you touch a field
});

find returns null when the row does not exist. getReference returns a lightweight proxy without hitting the database, handy for setting a foreign key without loading the target. Reading by anything other than the ID is done with queries, covered in HQL later in the course. Finding the same ID twice in one session returns the very same object, and the second call does not touch the database. That is the persistence context at work (see entity states).

Update: change the object

Java
sessionFactory.inTransaction(session -> {
    Book book = session.find(Book.class, 1L);
    book.setTitle("Refactoring, 2nd edition");   // no save call
});                                              // commit -> UPDATE book SET pages=?, title=? WHERE id=?

There is no update call to make: a managed object that changes is detected at flush time ("dirty checking", see Flush and dirty checking). For an object that is detached (loaded in another session, perhaps sent over a web form), use merge:

Java
Book detached = ...;                      // loaded earlier, session closed
detached.setTitle("New title");
sessionFactory.inTransaction(session -> {
    Book managed = session.merge(detached);   // copies state onto a managed instance
});

merge returns the managed copy; keep working with the returned object, not the one you passed in.

Delete: remove

Java
sessionFactory.inTransaction(session -> {
    Book book = session.find(Book.class, 1L);
    session.remove(book);                    // DELETE FROM book WHERE id=?
});

remove needs a managed instance. Load it first (or use getReference) and then remove it.

Older tutorials use session.save(), session.update(), session.saveOrUpdate(), session.get() and session.delete(). These are Hibernate-specific, deprecated in modern versions and not part of the standard API. Use persist, merge, find and remove in new code.

Stand-in: a CRUD repository

This stand-in implements the four operations by hand with JDBC and prints the SQL each time. Notice the one-to-one relationship between your intent (create, read, update, delete) and the statement. Hibernate does this for you, and adds tracking, caching and batching.

Java Stand-in: CRUD with visible SQL

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.

Stand-in: "dirty checking" in miniature

In real Hibernate the update statement appears without you asking for it. The idea is simple: remember a snapshot when the object is loaded, compare at flush time, and write only if something changed. This stand-in keeps a snapshot and flushes automatically. The real implementation compares each property against the loaded state.

Java Stand-in: snapshot and flush

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.

Practical advice

  • Always do writes inside a transaction. Reads can use inSession.
  • After remove, or after the session is closed, do not keep using the object as if it were managed.
  • find returns null; handle it (or wrap it with Optional).
  • Do not call persist on an object that already has a database row; use merge for detached copies.
  • Turn on SQL logging while learning, and read the statements. They teach more than any diagram.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which Session method returns null when no row exists?

    find returns null if there is no row. getReference returns a proxy and fails later when the proxy is used.
  2. 2. How do you update a managed entity?

    Dirty checking compares the object with its loaded snapshot and issues the UPDATE automatically.
  3. 3. When should you use merge?

    merge returns a managed copy of the detached object; keep using the returned instance.
  4. 4. Which pair of calls is the modern replacement for save() and get()?

    persist and find are standard JPA methods; save and get are older Hibernate-specific ones.
  5. 5. Calling find(Book.class, 1L) twice in one session produces:

    The persistence context (first-level cache) returns the already managed object the second time.

Summary

  • persist creates, find reads, changes to managed objects update, remove deletes; merge re-attaches detached state.
  • Writes belong in a transaction; the SQL is sent when the session flushes.
  • Updates need no explicit call: dirty checking notices changes to managed entities.
  • The first-level cache means one object per row per session.
  • Avoid the old save, update, saveOrUpdate, get and delete methods in new code.

Next: Hibernate Configuration