因为它的主要目标是让一个休眠会话与当前的Spring事务相关联,而此时不存在。由于它现在存在(并且已经存在很长时间:即使在hibernate3包中也不鼓励使用HibenateTemplate),因此没有理由使用这个特定于Spring的类而不是用于获取与当前Spring事务绑定的会话。SessionFactory.getCurrentSession()
SessionFactory.getCurrentSession()
如果你使用Spring,那么你应该使用它的声明性事务管理,它允许你避免打开,提交,关闭和刷新。这一切都是由Spring自动完成的:
@Autowired
private SessionFactory sessionFactory;
@Transactional
public void someMethod() {
// get the session for the current transaction:
Session session = sessionFactory.getCurrentSession();
// do things with the session (queries, merges, persists, etc.)
}
在上面的示例中,事务将在方法调用之前启动(如果尚未启动);Spring将为事务创建一个会话,并且在事务提交之前自动刷新会话,当方法返回时,Spring将自动完成该会话。