admin管理员组

文章数量:1612097


使用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