This document discusses techniques for improving data persistence performance using JPA 2.1 and Hibernate. It covers analyzing performance issues, optimizing queries, caching, and entity fetching strategies. Specific techniques include using Hibernate statistics, native queries, fetch joins, named entity graphs, and the first- and second-level caches. The goal is to recognize and address performance problems early using Hibernate's features.
Report
Share
Report
Share
1 of 54
Download to read offline
More Related Content
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
4. Performance
• Recognize performance problems as early as possible
• Typical causes for performance problems
• Solving performance problems
www.thoughts-on-java.org
12. SlowSELECTs • In general no „real“ JPA or Hibernate problem
• Check generated SQL
• Check execution plan of the statement
• Check indexes
• Optimize SELECT statement
• Consider to use a native query
www.thoughts-on-java.org
13. NativeQuery • Reasons to use native queries:
• JPQL supports only a subset of SQL
• Database specific features
• Native queries return an Object[] for each row
• Needs to be mapped programmatically or declaratively
www.thoughts-on-java.org
19. FetchType
• Defines when the relationship will be fetched
• Static definition in entity mapping
www.thoughts-on-java.org
@ManyToMany(mappedBy="authors", fetch = FetchType.EAGER)
private Set<Book> books;
20. FetchType • Lazy
• Relationship gets loaded at first access
• Default for to-many relationships
• Eager
• Loads relationships immediately
• Default for to-one relationships
www.thoughts-on-java.org
21. Recommendations • To-many relationships
• Stick to the default mapping (FetchType.LAZY)
• Use eager fetching for specific queries, if required
• To-one relationships
• Check individually
• Default is fine in most of the cases
www.thoughts-on-java.org
23. N+1Select? • Most common cause for performance problems
• Lazy fetching of related entities creates too many queries
www.thoughts-on-java.org
List<Author> authors = this.em.createQuery("SELECT a FROM Author a",
Author.class).getResultList();
for (Author a : authors) {
System.out.println("Author " + a.getFirstName() + " " + a.getLastName()
+ " wrote " + a.getBooks().size() + “ Books.”));
}
24. Queryspecificfetching
• Fetch all required entities with one query
• Fetch Joins
• @NamedEntityGraph
• EntityGraph
www.thoughts-on-java.org
26. FetchJoin
• Use JOIN FETCH instead of JOIN in JPQL query
www.thoughts-on-java.org
List<Author> authors = this.em.createQuery(
"SELECT DISTINCT a FROM Author a JOIN FETCH a.books b",
Author.class).getResultList();
27. FetchJoin • Advantages
• Relationships gets loaded in same query
• Disadvantages
• Requires a special query for each use case
• Creates cartesian product
www.thoughts-on-java.org
29. NamedEntityGraph • Introduced in JPA 2.1
• Declaratively defines a graph of entities which will be loaded
• Graph is query independent
www.thoughts-on-java.org
31. NamedEntityGraph • Provide entity graph es hint
www.thoughts-on-java.org
EntityGraph graph = this.em.getEntityGraph("graph.AuthorBooks");
this.em.createQuery("SELECT DISTINCT a FROM Author a")
.setHint("javax.persistence.loadgraph", graph);
32. NamedEntityGraph • Fetch graph
• Eager loading for all elements of the graph
• Lazy loading for all other attributes
• Load graph
• Eager loading for all elements of the graph
• Loads all other attributes with their defined FetchType
• Hibernate always uses a load graph
• HHH-8776
www.thoughts-on-java.org
33. NamedEntityGraph • Advantages
• Query specific EAGER loading
• Definition of the graph is independent of the query
• Disadvantages
• Creates cartesian product
www.thoughts-on-java.org
35. EntityGraph • Introduced in JPA 2.1
• Dynamic version of @NamedEntityGraph
• Definition via Java API
• Graph is query independent
www.thoughts-on-java.org
36. EntityGraph • Define and use EntityGraph
www.thoughts-on-java.org
EntityGraph graph = this.em.createEntityGraph(Author.class);
Subgraph<Book> bookSubGraph = graph.addSubgraph(Author_.books);
bookSubGraph.addSubgraph(Book_.reviews);
this.em.createQuery("SELECT DISTINCT a FROM Author a")
.setHint("javax.persistence.loadgraph", graph);
37. EntityGraph • Advantages
• Query specific EAGER loading
• Definition of the graph is independent of the query
• Dynamic creation at runtime
• Disadvantages
• Creates cartesian product
www.thoughts-on-java.org
41. 1stLevelCache
• Activated by default
• Linked to the Hibernate session
• Stores all entities that were used within a session
• Transparent usage
www.thoughts-on-java.org
43. 2ndLevelCache • Session independent entity store
• Needs to be activated
• persistence.xml or EntityManagerFactory
• Transparent usage
• PersistenceProvider doesn‘t need to provide it
• Not always portable
www.thoughts-on-java.org
44. 2ndLevelCache • Shared Cache Mode
• ALL cache all entities
• NONE cache no entities
• ENABLE_SELECTIVE cache needs to be activated for
specific entities
• DISABLE_SELECTIVE cache can be deactivated for specific
entities
• UNSPECIFIED use default settings of the
PersistenceProvider
www.thoughts-on-java.org
45. 2ndLevelCache • Cache configuration
• Cache Retrieve Mode
• How to read entities from the cache
• Cache Store Mode
• How to write entities to the cache
• Concurrency Strategy
• How to handle concurrent access
www.thoughts-on-java.org
47. QueryCache • Hibernate specific
• Stores query result session independent
• Needs to be activated (persistence.xml)
• hibernate.cache.use_query_cache = true
• Activate caching for a specific query
• org.hibernate.Query.setCacheable(true)
• @NamedQuery(… hints =
@QueryHint(name="org.hibernate.cacheable", value="true"))
www.thoughts-on-java.org
48. QueryCache • Stores query results for a query and its parameters
• [„FROM Author WHERE id=?“, 1] [1]
• Stores only entity references or scalars
• Always use together with 2nd Level Cache
www.thoughts-on-java.org
49. Recommendations • Only cache data that is seldom updated
• Always benchmark the application when adding or changing
caching
• Use Query Cache together with 2nd Level Cache
• Configuration has to fit to each other
www.thoughts-on-java.org
51. Get this presentation and a handy cheat sheet:
http://www.thoughts-on-java.org/javaland2016/
Follow me on twitter:
@thjanssen123
www.thoughts-on-java.org
54. Resources • Java Persistence with Hibernate Second Edition by Christian
Bauer, Gaving King, Gary Gregory
• Java Platform, Enterprise Edition: The Java EE Tutorial
https://docs.oracle.com/javaee/7/tutorial/index.html
• Hibernate: Truly Understanding the Second-Level and
Query Caches
http://www.javalobby.org/java/forums/t48846.html
www.thoughts-on-java.org