Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 39 ยท Testing and Best Practices

Hibernate Best Practices and Anti-Patterns

A checklist of Hibernate best practices - lazy associations, equals and hashCode, DTO projections, open-in-view, batching and schema control - and the anti-patterns to avoid.

Hibernate is easy to start and easy to misuse. Most production problems come from a short list of habits: eager associations, entities used as API objects, equals that breaks in a Set, work done outside transactions, and query counts nobody measures. This lesson collects the rules that prevent them. Each rule has a reason, so you can judge exceptions yourself.

Hibernate is not available in the browser, so mapping code is read-only. Where a behaviour can be shown without it, a short runnable Java program demonstrates the principle.

Mapping

  1. Make every association lazy. @ManyToOne and @OneToOne are eager by default in JPA; write fetch = FetchType.LAZY on them. Decide per query what to fetch with join fetch or entity graphs (see N+1 Queries and Fetch Strategies).
  2. Own the relationship from the many side. Map @ManyToOne and make @OneToMany(mappedBy = ...) the inverse side. Provide helper methods (addReview, removeReview) that keep both sides in sync.
  3. Prefer Set or an @OrderColumn list over a bag for large collections; deleting from an unordered List can rewrite the whole collection. Avoid huge collections altogether: a @OneToMany of a million rows should be a query with paging.
  4. Cascade deliberately. CascadeType.ALL plus orphanRemoval is right for true parts of an aggregate (order lines), wrong for shared entities. Never cascade REMOVE toward a parent that others reference.
  5. Use @Enumerated(EnumType.STRING) (or a converter). Ordinal values break when someone reorders the enum.
  6. Use proper types: java.time types, BigDecimal for money with explicit precision and scale, @Column(nullable = false, length = ...) that mirrors the real schema.
  7. Version rows that users edit with @Version.
  8. Own the schema with migrations (Flyway or Liquibase). Use hbm2ddl.auto=validate in production and none or update never.

Identity and equals/hashCode

Entities live in Sets, maps and the persistence context, so equals and hashCode matter. Three safe patterns:

  • Natural business key (ISBN, email) that is immutable and always set.
  • Generated id, with equals comparing ids only when both are non-null and hashCode returning a constant per class (getClass().hashCode()), so the hash does not change when the id is assigned on persist.
  • UUID assigned in the constructor, which is equal before and after saving.

Never include lazy associations or mutable fields in them, and compare classes with Hibernate.getClass(this) because proxies are subclasses.

Java hashCode based on a generated id breaks HashSet

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.

Queries and fetching

  • Fetch what the use case needs, no more. For read-only screens, project into DTOs or records (select new ..., or Tuple) and skip the entity machinery.
  • Never fetch-join a collection together with paging: Hibernate loads everything and pages in memory (HHH000104 warning). Page the parent ids first, then fetch their collections.
  • Join-fetch at most one collection per query, or you build a Cartesian product (MultipleBagFetchException).
  • Use bind parameters, never string concatenation, for every value that comes from users.
  • Batch fetching as a safety net: hibernate.default_batch_fetch_size=16 turns many lazy single-row loads into a few in (...) queries.
  • Measure. Count statements in tests (see Testing Hibernate Code) and read the slow query log.

Sessions and transactions

  • One transaction per use case, opened at the service layer, short and without remote calls inside.
  • Avoid open-in-view. In Spring Boot, spring.jpa.open-in-view defaults to true and keeps a session open through the view rendering, hiding N+1 queries and holding a connection while the response is written. Set it to false and fetch what the view needs in the service.
  • Never share a Session or entity manager between threads. SessionFactory is shared; sessions are not.
  • Do not return entities from REST controllers. They expose lazy proxies, bidirectional cycles and internal fields; map to DTOs.
  • Do not catch and swallow Hibernate exceptions inside a transaction, because the session state is unreliable after an error.
  • merge is not "save": it copies state onto a managed instance. For new entities use persist; for existing managed ones just change the fields.
Java Exposing lazy data after the session closes (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.

Quick anti-pattern table

Anti-pattern Why it hurts Instead
FetchType.EAGER on collections loads data nobody asked for lazy + explicit fetching
Entities as JSON lazy errors, cycles, leaks DTOs
CascadeType.ALL everywhere accidental deletes cascade only inside aggregates
@Transactional on controllers long transactions with view work inside service-level boundaries
findAll() then filter in Java loads the whole table query with where and paging
Lombok @Data on entities equals/hashCode/toString touch lazy fields hand-written equals, no associations in toString
hbm2ddl=update in production unreviewed schema changes migrations
Ignoring the second session.find returning the same object confusion about state learn the persistence context

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is hashCode based on a generated id problematic in a HashSet?

    Changing the hash while the object is in a hash-based collection makes lookups fail.
  2. 2. What is wrong with fetch-joining a collection and paging with setMaxResults?

    Rows are multiplied by the collection size, so the database limit would cut parents; Hibernate pages in memory instead.
  3. 3. Why set spring.jpa.open-in-view=false?

    With it off, missing fetches surface as errors during development instead of silent extra queries.
  4. 4. Which enum mapping is safest?

    STRING survives reordering of enum constants; ORDINAL silently changes meaning.

Summary

  • Keep associations lazy, own them from the many side, cascade only inside aggregates, map enums as strings and version edited rows.
  • Write equals and hashCode that survive the transient-to-persistent transition.
  • Fetch per use case, project to DTOs, never page a join-fetched collection, and measure statement counts.
  • Keep transactions at the service layer, switch off open-in-view and never expose entities through your API.

Next: Project: A Library Repository Layer