Menu

Best Practices and Common Mistakes

Best Practices and Common Mistakes

Most Hibernate problems come from a small set of repeated mistakes. The table lists the common ones with the better choice.

Mistake

Better practice

Leaving @ManyToOne and @OneToOne eagerSet FetchType.LAZY and fetch what each query needs
Ignoring the N+1 problemUse join fetch, entity graphs, or @BatchSize, and check the SQL log
Storing enums with ORDINALUse EnumType.STRING
Using a List for many-to-manyUse a Set
CascadeType.ALL on shared entitiesCascade only from a parent to children it owns
Returning entities from REST endpointsReturn DTOs, which avoids lazy loading errors and unwanted fields
Using update in productionUse Flyway or Liquibase with validate
Lombok @Data on entitiesWrite equals, hashCode, and toString carefully, since a generated toString can load lazy data or loop through bidirectional links
Long transactions and sessionsKeep them short and around one unit of work
Built-in connection handlingUse a connection pool such as HikariCP
Unsafe concurrent updatesAdd @Version on entities that several users edit

Hibernate Tutorial

AP

Abhishek Pati



Learn via Video Course

Java Programming ( Telugu) Logo

Java Programming ( Telugu)

11 hrs



Get in Touch For Details