admin管理员组文章数量:1612099
使用hibernate4的SessionFactory获取Session时有两种方式
1、sessionFactory.getCurrentSession()
2、sessionFactory.openSession(),开启新session,需要关闭
当使用1获取CurrentSession,不会开启新的session,速度很快。
但是如果你是使用多线程的时候,就不能使用getCurrentSession,这样会报以下错误:HibernateException: Could not obtain transaction-synchronized Session for current thread
这是因为这spring事务中,在一个线程中获取的connection都是同一个,并且用threadlocal存储这个connnection.如果在多线程中,那就不是在同一个线程中了,因此就会发生上述的问题。
解决方案一:
将getCurrentSession()需要改成openSession()方式就可以解决了
方案二:
新建一个class文件,把操作数据库的代码写在这里,并且添加@Transactional,就可以了。
本文标签: 多线程obtainHibernateExceptionTransactionthread
版权声明:本文标题:多线程出现HibernateException: Could not obtain transaction-synchronized Session for current thread 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728630294a1167009.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论