22
1 Hibernate Performance Hibernate Performance Strategies Strategies

Hibernate Join Fetch

Embed Size (px)

Citation preview

Page 1: Hibernate Join Fetch

1

Hibernate PerformanceHibernate PerformanceStrategiesStrategies

Page 2: Hibernate Join Fetch

2

Topics

● Fetching modes● Lazy fetching● N+1 query problem● Monitoring

Page 3: Hibernate Join Fetch

3

Fetching StrategiesFetching Strategies

Page 4: Hibernate Join Fetch

4

What is a Fetching Strategy?

● A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association.

● Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

Page 5: Hibernate Join Fetch

5

Supported Fetching Strategies

● Join fetching● Select fetching● Subselect fetching● Batch fetching

Page 6: Hibernate Join Fetch

6

Join Fetching

● Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN

Page 7: Hibernate Join Fetch

7

Select Fetching

● Default● Vulnerable to N+1 selects problem– “N” number of SELECT's are used to retrieve the

associated entity or collection.● Unless you explicitly disable lazy fetching by

specifying lazy="false", the subsequent select will only be executed when you actually access the association.

Page 8: Hibernate Join Fetch

8

Subselect Fetching

● A second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch.

● Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.

Page 9: Hibernate Join Fetch

9

Batch Fetching

● An optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

Page 10: Hibernate Join Fetch

10

Tuning fetch strategies

● Select fetching (the default) is extremely vulnerable to N+1 selects problems, so we might want to enable join fetching in the mapping document:<set name="permissions" fetch="join"> <key column="userId"/> <one-to-many class="Permission"/></set

Page 11: Hibernate Join Fetch

11

Lazy FetchingLazy Fetching

Page 12: Hibernate Join Fetch

12

Lazy Fetching

● A collection is fetched when the application invokes an operation upon that collection

● Default for collections

Page 13: Hibernate Join Fetch

13

Avoiding N+1 SelectAvoiding N+1 SelectProblem Problem

Page 14: Hibernate Join Fetch

14

Problem Description

● Suppose we have a class Supplier with a one-to-many relationship with Product. – One supplier can be related to many products

● Lets suppose we want to list the name of the products, but for the purposes of this query we do not care about any of the manufacturer's supplier information. We simply run the query– Query query = session.createQuery( "from Product p");– List list = query.list();– //do something with the list of Product instances

Page 15: Hibernate Join Fetch

15

Problem Description

● The query Hibernate generates is– select ... various field names ... from PRODUCT

● Then, another set of queries are performed by Hibernate – this N+1 problem– select ... various field names ... from SUPPLIER where

SUPPLIER.id=?– select ... various field names ... from SUPPLIER where

SUPPLIER.id=?– select ... various field names ... from SUPPLIER where

SUPPLIER.id=?

Page 16: Hibernate Join Fetch

16

Solution

● Make the Supplier class lazy, simply by enabling the lazy attribute in the Supplier's hbm.xml mapping definition file.<class name="Supplier" table="SUPPLIER" lazy = "true">...</class>

● In Hibernate 3, this is default● Only one select statement is executed● Now, when Supplier is accessed, then we have a

problem

Page 17: Hibernate Join Fetch

17

MonitoringMonitoringPerformancePerformance

Page 18: Hibernate Join Fetch

18

Statistics

● Hibernate provides a full range of figures about its internal operations.

● Statistics in Hibernate are available per SessionFactory.– Option1: Call sessionFactory.getStatistics() and read

or display the Statistics yourself.– Option2: Through JMX

Page 19: Hibernate Join Fetch

19

Statistics Interface

● Hibernate provides a number of metrics, from very basic to the specialized information only relevant in certain scenarios.

● All available counters are described in the Statistics interface API, in three categories:– Metrics related to the general Session usage, such

as number of open sessions, retrieved JDBC connections, etc.

– Metrics related to he entities, collections, queries, and caches as a whole (aka global metrics),

– Detailed metrics related to a particular entity, collection, query or cache region.

Page 20: Hibernate Join Fetch

20

Statistics Interface

Page 21: Hibernate Join Fetch

21

Example Code

Statistics stats = HibernateUtil.sessionFactory.getStatistics();

double queryCacheHitCount = stats.getQueryCacheHitCount();double queryCacheMissCount = stats.getQueryCacheMissCount();double queryCacheHitRatio = queryCacheHitCount / (queryCacheHitCount +

queryCacheMissCount);

log.info("Query Hit ratio:" + queryCacheHitRatio);

EntityStatistics entityStats = stats.getEntityStatistics( Cat.class.getName() );long changes = entityStats.getInsertCount() + entityStats.getUpdateCount() + entityStats.getDeleteCount();log.info(Cat.class.getName() + " changed " + chang

Page 22: Hibernate Join Fetch

22

Hibernate PerformanceHibernate PerformanceStrategiesStrategies