Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Testing and Best Practices

Testing Hibernate Code

Test Hibernate repositories with real databases, Testcontainers, rollback-per-test isolation, query-count assertions and N+1 guards, and know what H2 cannot prove.

Mapping code is full of things that compile and still fail at runtime: a wrong column name, a missing cascade, a lazy collection read after the session closed, a query that issues 101 statements. Mocks cannot find these problems because they replace the very thing that is wrong. Persistence code needs tests that run against a real database. This lesson shows how to set those up and what to assert.

Hibernate, JUnit and Testcontainers are not available in the browser, so their code is read-only. The runnable programs build a tiny test harness (setup, rollback per test, statement counting) on JDBC and H2, which is the mechanism those tools use.

What to test

Test Purpose
Mapping test persist, flush, clear, reload: do all fields and associations survive?
Query test does each repository query return the right rows, in the right order, with the right fetch?
Constraint test does the schema reject duplicates and orphan rows?
Performance guard does the use case issue at most N statements?
Concurrency test does a stale version really fail?

Business rules should live in plain classes that need no database at all. Keep the Hibernate tests for what only Hibernate and the database can answer.

Real database beats a fake

H2 or HSQLDB in memory is fast and good for mapping tests, but it is not your production database: different SQL dialect details, no PostgreSQL JSON or arrays, different locking, different default isolation, different case rules. Tests that pass on H2 and fail in production are common.

Prefer Testcontainers to start the same engine you deploy, in Docker, for the test run:

Java
@Testcontainers
class BookRepositoryTest {
    @Container
    static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:17");

    static SessionFactory sessionFactory;

    @BeforeAll
    static void start() {
        sessionFactory = new Configuration()
            .addAnnotatedClass(Book.class)
            .setProperty("hibernate.connection.url", db.getJdbcUrl())
            .setProperty("hibernate.connection.username", db.getUsername())
            .setProperty("hibernate.connection.password", db.getPassword())
            .setProperty("hibernate.hbm2ddl.auto", "create-drop")
            .buildSessionFactory();
    }
}

Start the container once per test class (a static field) and reuse it, because starting a database costs seconds. For Spring Boot, @DataJpaTest with @AutoConfigureTestDatabase(replace = NONE) plus @ServiceConnection on the container wires everything.

Use H2 for quick feedback if you must, but run the same suite against the real engine in CI. Create the schema from migrations (Flyway or Liquibase) in tests so the migration scripts are tested too; hbm2ddl=create-drop only proves your annotations agree with themselves.

Isolate tests

Each test must start from a known state. Two common approaches:

  1. Rollback per test: begin a transaction in @BeforeEach, roll it back in @AfterEach. Fast, but the test then never commits, so it cannot see constraint checks deferred to commit or behaviour that depends on a real commit.
  2. Truncate between tests or recreate the schema: slower, but exercises real commits.

Spring's @Transactional on a test class does approach 1 automatically. Beware the classic trap: inside one transaction the persistence context hides bugs. If you persist and then find, you get the cached instance, no SQL runs and no mapping is checked. Always flush() and clear() before reading back:

Java
session.persist(book);
session.flush();          // force the INSERT now
session.clear();          // drop the first-level cache
Book loaded = session.find(Book.class, book.getId());
assertEquals("Engines", loaded.getTitle());   // read from the database
Java A mini test harness with rollback per test (stand-in)

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.

Guard against N+1 with a statement counter

Assert on the number of statements a use case issues. Hibernate statistics give you the count:

Java
@Test
void listingBooksUsesOneQuery() {
    Statistics stats = sessionFactory.getStatistics();
    stats.setStatisticsEnabled(true);
    stats.clear();

    List<BookDto> dtos = service.listBooksWithAuthors();

    assertEquals(1, stats.getPrepareStatementCount(), "N+1 detected");
}

Libraries such as datasource-proxy or hypersistence-utils offer assertSelectCount(1) on the JDBC level, which also catches statements Hibernate statistics miss. Put a ceiling, not an exact number, on use cases that legitimately vary.

Java Assert a statement budget (stand-in)

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.

Other practical tips

  • Build test data with small builders or object mothers (aBook().withAuthor(anAuthor())), not giant SQL scripts.
  • Test both sides of a lazy association: use Hibernate.isInitialized(entity.getReviews()) to prove a query fetched what you wanted.
  • Test equals and hashCode of entities across states (see Hibernate Best Practices and Anti-Patterns).
  • Test optimistic locking with two sessions: load in both, change in one and commit, then expect the second to fail.
  • Turn on hibernate.show_sql only while debugging; prefer logging category org.hibernate.SQL at DEBUG and org.hibernate.orm.jdbc.bind at TRACE for parameters.
  • Keep tests independent of ordering and of generated ids.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why call flush() and clear() before reading an entity back in a test?

    Without them the first-level cache returns the same object and the mapping is never verified.
  2. 2. What is the main risk of testing only against H2 when production uses PostgreSQL?

    Passing on H2 does not prove behaviour on the real engine; Testcontainers runs the real one.
  3. 3. How can a test detect an N+1 regression?

    A statement-count assertion fails as soon as a loop starts issuing one query per row.
  4. 4. Which belongs in a plain unit test without a database?

    Pure business rules need no persistence; keep database tests for mapping, queries and constraints.

Summary

  • Test persistence against a real database; use Testcontainers for the production engine and migrations for the schema.
  • Isolate tests by rollback or truncation, and flush plus clear before reading back.
  • Assert statement counts to catch N+1 problems, and test constraints and optimistic locking explicitly.
  • Keep business rules in plain classes with ordinary unit tests.

Next: Hibernate Best Practices and Anti-Patterns