I am trying to improve a hibernate webapp written by others that is performing terribly. I turned on showSQL in the properties and am shocked by how many unnecessary queries it makes, as well as the fact that it updates every field of every row regardless of dirty-ness. Among many problems one that my co-worker and I think is a major contributor is that the app tends to call hibernateTemplate.method() for most of it's behaviors. Does this create a new session each time and therefore hibernate doesn't know how to reduce workload (dirty, duplicate queries etc)?
In addition to asking the question, i want to get a logging into the session creation and checkout process so that I can echo out how often sessions are created. I have one on the datasource where connections are created and can see connections being checked out way to often. I was hoping that I could do the same with the session to prove the point. the app uses AnnotationSessionFactoryBean for it's session factory and I subclassed it and overrode the wrapSessionFactoryIfNecessary method, but it never gets called. How can I get some logging in there?
Well unless you are working with a legacy application using a really old version of Hibernate and Spring, then the ORM Template classes (like HibernateTemplate) are no longer the accepted pattern, rather you should use the Hibernate API directly.
I would start with just making sure that Hibernate and Spring are being integrated correctly.
Once you have gone through that you can re-assess.
For the query piece make sure you are not lazy loading where you should be eager loading or using fetch queries. For example if you know you are going to have to iterate over a collection and access every object in it don't lazy load it or hibernate will be issuing a select for every element as its accessed.
If you are using session.update() it will trigger an update if the entity was detached regardless of whether it has changed or not. This is because when it is reattached it is automatically marked as dirty. Consider using merge() instead to avoid this.
There are many ways to use a library like Hibernate improperly I am afraid a lot of it is just going to be wading through finding the bottlenecks and issues and addressing them.