Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lect17-hibernate-orm / more / hibernate_reference.pdf
Скачиваний:
63
Добавлен:
18.03.2015
Размер:
2.2 Mб
Скачать

Chapter 21. Improving performance

idiom, for example, we can add elements to a bag or list without needing to initialize (fetch) the bag elements. This is because, unlike a set, Collection.add() or Collection.addAll() must always return true for a bag or List. This can make the following common code much faster:

Parent p = (Parent) sess.load(Parent.class, id);

Child c = new Child();

c.setParent(p);

p.getChildren().add(c); //no need to fetch the collection!

sess.flush();

21.5.4. One shot delete

Deleting collection elements one by one can sometimes be extremely inefficient. Hibernate knows not to do that in the case of an newly-empty collection (if you called list.clear(), for example). In this case, Hibernate will issue a single DELETE.

Suppose you added a single element to a collection of size twenty and then remove two elements. Hibernate will issue one INSERT statement and two DELETE statements, unless the collection is a bag. This is certainly desirable.

However, suppose that we remove eighteen elements, leaving two and then add thee new elements. There are two possible ways to proceed

delete eighteen rows one by one and then insert three rows

remove the whole collection in one SQL DELETE and insert all five current elements one by one

Hibernate cannot know that the second option is probably quicker. It would probably be undesirable for Hibernate to be that intuitive as such behavior might confuse database triggers, etc.

Fortunately, you can force this behavior (i.e. the second strategy) at any time by discarding (i.e. dereferencing) the original collection and returning a newly instantiated collection with all the current elements.

One-shot-delete does not apply to collections mapped inverse="true".

21.6. Monitoring performance

Optimization is not much use without monitoring and access to performance numbers. Hibernate provides a full range of figures about its internal operations. Statistics in Hibernate are available per SessionFactory.

21.6.1. Monitoring a SessionFactory

You can access SessionFactory metrics in two ways. Your first option is to call sessionFactory.getStatistics() and read or display the Statistics yourself.

344

Metrics

Hibernate can also use JMX to publish metrics if you enable the StatisticsService MBean. You can enable a single MBean for all your SessionFactory or one per factory. See the following code for minimalistic configuration examples:

// MBean service registration for a specific SessionFactory Hashtable tb = new Hashtable();

tb.put("type", "statistics"); tb.put("sessionFactory", "myFinancialApp");

ObjectName on = new ObjectName("hibernate", tb); // MBean object name

StatisticsService stats = new StatisticsService(); // MBean implementation stats.setSessionFactory(sessionFactory); // Bind the stats to a SessionFactory server.registerMBean(stats, on); // Register the Mbean on the server

// MBean service registration for all SessionFactory's Hashtable tb = new Hashtable();

tb.put("type", "statistics"); tb.put("sessionFactory", "all");

ObjectName on = new ObjectName("hibernate", tb); // MBean object name

StatisticsService stats = new StatisticsService(); // MBean implementation server.registerMBean(stats, on); // Register the MBean on the server

You can activate and deactivate the monitoring for a SessionFactory:

• at configuration time, set hibernate.generate_statistics to false

• at

runtime:

sf.getStatistics().setStatisticsEnabled(true)

or

hibernateStatsBean.setStatisticsEnabled(true)

Statistics can be reset programmatically using the clear() method. A summary can be sent to a logger (info level) using the logSummary() method.

21.6.2. Metrics

Hibernate provides a number of metrics, from basic information to more specialized information that is 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 the entities, collections, queries, and caches as a whole (aka global metrics).

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

For example, you can check the cache hit, miss, and put ratio of entities, collections and queries, and the average time a query needs. Be aware that the number of milliseconds is subject to

345

Chapter 21. Improving performance

approximation in Java. Hibernate is tied to the JVM precision and on some platforms this might only be accurate to 10 seconds.

Simple getters are used to access the global metrics (i.e. not tied to a particular entity, collection, cache region, etc.). You can access the metrics of a particular entity, collection or cache region through its name, and through its HQL or SQL representation for queries. Please refer to the

Statistics, EntityStatistics, CollectionStatistics, SecondLevelCacheStatistics, and

QueryStatistics API Javadoc for more information. The following code is a simple example:

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 " + changes + "times" );

You can work on all entities, collections, queries and region caches, by retrieving the list of names of entities, collections, queries and region caches using the following methods: getQueries(), getEntityNames(), getCollectionRoleNames(), and getSecondLevelCacheRegionNames().

346

Соседние файлы в папке more