Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Hibernate Practice Questions and Debugging Drills

Test what you learned with Hibernate practice questions, debugging drills for common exceptions, a query-tuning exercise and interview-style answers.

You have covered mapping, sessions, queries, caching and concurrency. This closing lesson is a workout: first a debugging table of exceptions you will meet at work, then three small drills, then a quiz in the style of interview questions. Try to answer before you read the explanations.

Hibernate is not available in the browser, so its code is read-only. The runnable drills use JDBC and plain Java to reproduce the underlying problems.

Exceptions and what they usually mean

Message Likely cause First thing to try
LazyInitializationException: could not initialize proxy - no Session touching a lazy association after the session closed fetch it in the query (join fetch) or map to a DTO inside the transaction
MultipleBagFetchException fetch-joining two List collections fetch one collection per query, or use Set, or batch fetching
TransientObjectException / TransientPropertyValueException an entity references another that is not saved persist the child first, or add cascade = PERSIST
StaleObjectStateException, OptimisticLockException version mismatch: concurrent update reload and redo; show the user the conflict
NonUniqueObjectException two different instances with the same id in one session use the one the session already holds, or merge
DetachedEntityPassedToPersistException persist on an entity that already has an id use merge, or load a managed instance
ConstraintViolationException unique, not-null or foreign key violated read the constraint name; fix the data or the logic
org.hibernate.PropertyValueException: not-null property references a null a nullable=false field is null at flush set it before flush
HHH000104: firstResult/maxResults specified with collection fetch paging plus a join-fetched collection (in-memory paging) page ids first, then fetch
QuerySyntaxException: Book is not mapped entity name is wrong in HQL (it is the class name, not the table) use the entity name
LockTimeoutException waited too long for a lock find the blocking transaction; shorten transactions
could not execute statement ... Data too long string longer than column length align @Column(length) and the schema

Debugging method: reproduce, then look at the SQL (org.hibernate.SQL at DEBUG, parameters at TRACE). Most Hibernate puzzles become obvious once you read the statements it sends.

Drill 1: spot the N+1

A report prints each author's book count:

Java
List<Author> authors = session.createQuery("from Author", Author.class).getResultList();
for (Author a : authors) {
    System.out.println(a.getName() + ": " + a.getBooks().size());
}

With 1,000 authors this issues 1,001 statements. Fix it three ways: join fetch, a DTO query with count, or batch fetching. Which is best for a report? The DTO query, because the report never needs the books themselves:

Java
select new AuthorCount(a.name, count(b)) from Author a left join a.books b group by a.name
Java Drill: count the statements for both approaches

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.

Drill 2: why does this lose an update?

Java
Product p = session.find(Product.class, id);
p.setStock(p.getStock() - qty);

Two requests run it together on stock 10, each with qty = 3. Both read 10, both write 7. Expected final stock is 4. Fixes, from lightest to heaviest: an atomic update product set stock = stock - :q where id = :id and stock >= :q; @Version with a retry; PESSIMISTIC_WRITE on the find. Which would you choose in an online shop? The atomic update when only a counter changes; @Version when the whole product is edited.

Drill 3: dirty checking surprise

Java
@Transactional
public void report() {
    List<Book> books = repo.findAll();
    for (Book b : books) {
        b.setTitle(b.getTitle().trim());      // "just for display"
    }
}

No save call, yet an update runs for every book whose title had spaces. Because the entities are managed, dirty checking writes the changes at flush. Fix: use a DTO or @Transactional(readOnly = true), or detach the entities before editing.

Java Drill: simulate dirty checking by comparing snapshots

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.

Interview-style answers in one sentence

  • Session vs SessionFactory: the factory is a heavyweight, thread-safe, one-per-database object; a session is a lightweight, single-threaded unit of work holding the persistence context.
  • get vs load / find vs getReference: the first hits the database now and returns null if missing; the second returns a proxy that loads on first use.
  • persist vs merge: persist makes a new instance managed; merge copies the state of a detached instance onto a managed copy and returns it.
  • First-level vs second-level cache: L1 is per session and always on; L2 is per factory, opt-in, and stores disassembled state.
  • Lazy vs eager: lazy delays loading until access; eager loads with the owner and is a frequent source of N+1.
  • Optimistic vs pessimistic: version check at commit versus database lock at read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A report loops over authors and calls getBooks().size(). What is the best fix when only counts are needed?

    The aggregate query returns exactly the numbers in one statement without loading the books.
  2. 2. Why did a method with no save call issue UPDATE statements?

    Changes to managed entities are detected by comparing snapshots at flush.
  3. 3. Which exception signals that persist was called on an entity that already has an id?

    Use merge for detached instances, persist for new ones.
  4. 4. What is the difference between persist and merge?

    After merge you must use the returned instance, because the argument itself stays detached.
  5. 5. Which two settings reveal the SQL and bind values for debugging?

    The SQL category prints statements, and the JDBC bind logger shows parameter values.

Summary

  • Match common Hibernate exceptions to their causes quickly, and read the generated SQL first.
  • Fix N+1 with the cheapest correct tool: DTO aggregates, join fetch, or batch fetching.
  • Remember that managed entities are written back automatically; use read-only transactions and DTOs for reports.
  • Know the core contrasts: session vs factory, persist vs merge, L1 vs L2, lazy vs eager, optimistic vs pessimistic.

Back to the course: Hibernate ORM