I am prefectionist!

Moje zdjęcie
Piaseczno, mazowieckie, Poland

wtorek, 17 czerwca 2008

Hibernate: to obtain fetch_size / batch_size / default_batch_fetch_size / etc. programmatically

The question is:
How to obtain (during runtime) fetch_size / batch_size / default_batch_fetch_size / etc. programmatically when the only thing I have is a reference to EntityManagerFactory?

Here is my proposition:
EntityManagerFactory mainEmf = ...;
(...)
final HibernateEntityManagerFactory hibernateEntityManagerFactory = (HibernateEntityManagerFactory) mainEmf;
final SessionFactory sessionFactory = hibernateEntityManagerFactory.getSessionFactory();
SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) sessionFactory;
final Settings settings = sessionFactoryImplementor.getSettings();

final int jdbcBatchSize = settings.getJdbcBatchSize();
final int jdbcFetchSize = settings.getJdbcFetchSize();
final int defaultBatchFetchSize = settings.getDefaultBatchFetchSize();



Why, the hell, I want to have those values?
Well... There is at least one reason :)

In the Hibernate documentation, we can find a piece of code (13.1. Batch inserts):
for ( int i=0; i<100000; i++ ) {
Customer customer = new Customer(.....);
session.save(customer);
if ( i %
20 == 0 ) { //20, same as the JDBC batch size
//flush a batch of inserts and release memory:
session.flush();
session.clear();
}
}
As we can see, in this example it is good to know the size of predefined value for JDBC batch size (defined in hibernate.cfg.xml file). For performance reasons those values (in the hibernate.cfg.xml fiel and in our Java sources) should be equal.
This trick avoids me to change Java source code when I'm going to change my JDBC batch size (such situation is quite usual when trying to find optimal setting for JDBC batch size).

Well... I don't think that this trick is a simplest way to get those values programmatically. If someone has better solution - give a piece of code as a comment :)

Regards,
Adam

Brak komentarzy: