hibernate、session、事务

@Repository
public class XdoDaoSupport implements XdoDao {
  @Autowired
  @Qualifier("sessionFactory")
  private SessionFactory sessionFactory;

  public XdoDaoSupport() {
  }

  public Session getSession() {
    return this.sessionFactory.getCurrentSession();
  }
}

测试:
System.out.println(xdoDaoSupport.getSession().isOpen());

通过上述方法获取session,会报错,报错信息如下:

org.springframework.orm.hibernate4.HibernateSystemException: Could not obtain transaction-synchronized Session for current thread; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
	at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:218)
	at org.springframework.orm.hibernate4.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:57)
	at org.springframework.orm.hibernate4.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:44)
	at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
	at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655)
	at com.xms.xpo.base.dao.hibernate.XdoDaoSupport$$EnhancerBySpringCGLIB$$c6f22f9b.getSession(<generated>)

报错原因:未将session纳入事务管理,解决办法如下:

@Service
@Transactional
public class BaseManagerImpl implements BaseManager {
  @Autowired
  private XdoDao xdoDao;

  public BaseManagerImpl() {
  }

  public Session getSession() {
    return this.xdoDao.getSession();//可以获取session
  }
}

事务在执行完成后会自动关闭session!!!

所以,当在其他处调用该方法时,会出现该session已关闭的错误,需注意:

其他类中调用
@Autowired
BaseManager baseManager;
System.out.println(baseManager.getSession().isOpen());//false

如需在其他类中调用,则需在该类中加入事务管理,来覆盖BaseManagerImpl的事务,以避免关闭session

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值