因为它的主要目的是使Hibernate会话绑定到当前的Spring事务(如果
SessionFactory.getCurrentSession()不存在)。由于它已经存在(并且很长一段时间:即使在hibernate3软件包中也不鼓励使用HibenateTemplate),因此没有理由使用该特定于Spring的类,而不是使用
SessionFactory.getCurrentSession()将会话绑定到当前Spring事务。
如果使用Spring,则应使用其声明式事务管理,这样可以避免打开,提交,关闭和刷新。这一切都是由Spring自动完成的:
@Autowiredprivate SessionFactory sessionFactory;@Transactionalpublic void someMethod() { // get the session for the current transaction: Session session = sessionFactory.getCurrentSession(); // do things with the session (queries, merges, persists, etc.)}在上面的示例中,将在方法调用之前启动事务(如果尚未启动)。Spring将为该事务创建一个会话,该会话将在事务提交之前自动刷新,该方法将在方法返回时由Spring自动完成。



