Spring provides Hibernate DAO tool class: HibernateDaoSupport. This class mainly provides two methods:
Public final HibernateTemplate getHibernateTemplate ()
Public final void setSessionFactory (SessionFactory sessionFactory)
The setSessionFactory method receives dependency injection from Spring's applicationContext and receives SessionFactory instances configured in Spring. The getHibernateTemplate method is used to generate a Session using the SessionFactory and then generate the HibernateTemplate to access the database.
The typical DAO code inheriting HibernateDaoSupport is as follows:
Public class UserDAOImpl extends HibernateDaoSupport implements UserDAO {
Public void save (Users transientInstance ){
Log. debug ("saving Users instance ");
Try {
GetHibernateTemplate (). save (transientInstance );
Log. debug ("save successful ");
} Catch (RuntimeException re ){
Log. error ("save failed", re );
Throw re;
}
}
..................
}
In fact, the DAO implementation still relies on the template access method of HibernateTemplate. However, HibernateDaoSupport has completed the work of injecting dependencies into SessionFactory and obtaining HibernateTemplate. Note that this method requires configuring SessionFactory in the Spring configuration file.
In the DAO implementation inherited by HibrnateDaoSupport, Hibernate Session management is managed by Spring instead of opening Hibernate code. Based on actual operations, Spring uses the "open session once every transaction" policy to automatically improve the performance of database access.
Author: huang798807481