Hibernate Performance Tips
Performance TIP-1
Let Hibernate collect internal statistics
Activate Hibernate Statistics
- Set hibernate.generate_statistics to true
- Set org.hibernate.stat log level to DEBUG
Hibernate will collect the insternal statistics for each session like no.of queries performed and time spent for them and no of cache hits and misses.
Performance TIP-2
Improve slow queries
- Slow queries are not JPA or Hibernate issue,
- Analyze SQL queries and execution plans
- Implement complex queries as native SQL queries.
Performance TIP-3
Choose the right Fetch Type
- It defines in the Entity mapping when an association get loaded
- Specified in Entity Mapping
@ManyToMany(mappedBy='authors', fetch=FetchType.LAZY)
List<Book> books; - Same fetch type for all use cases
Performance TIP-4
Query specific fetching
- Use eagar fetching for specific queries. ( We can avoid LazyInitializationExceptions and n+1 problem)
- we can do it in different ways
- Use FETCH JOIN in JPQL or Criteria Queries
- @NamedEntityGraph
- EntityGraph
Define:
-------
@Entity
@NamedEntityGraph(name="graph.AuthorBooks", attributeNodes= @NamedAttributeNode(value="books"))
public Author implements serializable{
}
Calling:
--------
EntityGraph<?> graph = em.createEntityGraph("graph.AuthorBooks")
TypedQuery<Author> q = em.createQuery("Select a from Author a where a.id=1, Author.class);
q.setHint("javax.persistence.fetchgraph", graph);
Author a = q.getSingleResult();
Performance TIP-5
Let database handle data-heavy operations
with simple operations
- Call functions in your queries
complex operations
- Call stored procedures
Performance TIP-6
Use caches to avoid reading the same data multiple times.
Performance TIP-7
Perform updates and deletes in bulks.
- Prefer bulk operations for multiple entities.
- JPQL update and delete statements
- CriteriaUpdate and CriteriaDelete
- SQL update and delete statements