HibernateCallback and getCurrentSession difference
Can I use geCurrentSession() instead of using HibernateCallback to get the session?. If both sessions are managed by Sprin开发者_StackOverflow社区g, why do I need a Callback ? Is there any performance advantage associated with this ?
In a well-configured Spring application, both are equivalent except in one case: when there is no current transaction context. In this case, getCurrentSession() won't work, whereas using a HibernateCallback will open a session and a Hibernate transaction for you and close them at the end.
Note that the documentation of HibernateTemplate mentions that getCurrentSession() should be preferred:
NOTE: As of Hibernate 3.0.1, transactional Hibernate access code can also be coded in plain Hibernate style. Hence, for newly started projects, consider adopting the standard Hibernate3 style of coding data access objects instead, based on SessionFactory.getCurrentSession().
It also says:
Note that HibernateTemplate will perform its own Session management, not participating in a custom Hibernate CurrentSessionContext unless you explicitly switch "allowCreate" to "false".
Mixing both ways of doing is thus not a good idea.
My preference is to avoid HibernateTemplate, use the Hibernate Session API directly, and use Spring-managed declarative transactions.
精彩评论