最近项目在整合后台框架,将原来的Spring3.2换为Spring4,Hibernate3换为Hibernate4,以前的Dao组件要做修改。
Spring3时代,为整合Hibernate3提供了HibernateTemplate,为Dao提供了工具类:HibernateDaoSupport。Spring4进行了扩展,不再推荐使用HibernateTemplate,HibernateDaoSupport来实现Dao组件,而是使用SessionFactory的getCurrentSession()获取session,然后进行持久化。
在实现Dao组件获取session时又遇到问题:
dao实现如下:
public T get(Class<T> entityClazz, Serializable id) {
return (T) sessionFactory.getCurrentSession().get(entityClazz, id);
}
启动后报错:
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:134)
如果将
sessionFactory.getCurrentSession().get(entityClazz, id);
换为
sessionFactory.openSession().get(entityClazz, id);
则显示正常,于是就查阅了一下两者的不同:
openSession ,是打开一个新的session对象,而且每次使用都是打开一个新的session,假如连续使用多次,则获得的session不是同一个对象,并且使用完需要调用close方法关闭session。
getCurrentSession ,是获取当前上下文一个session对象,当第一次使用此方法时,会自动产生一个session对象,并且连续使用多次时,得到的session都是同一个对象,并且事务提交会自动close,不需要像openSession一样自己调用close方法关闭session
所以,使用getCurrentSession 就要进行事务管理配置,以下是基于注解方式的事务管理配置:(注意导入aopaliance.jar)
org.hibernate.dialect.MySQL5Dialect true thread com.wcc.user.model @Service("userService") @Transactional public class UserServiceImpl implements IUserService { @Resource(name = "userDao") private IUserDao userDao; @Override public String test() { return userDao.test(); } @Override public Employee getEmployeeById(Integer id) { return userDao.getEmployeeById(id); } }