1. 程式人生 > >多執行緒出現HibernateException: Could not obtain transaction-synchronized Session for current thread

多執行緒出現HibernateException: Could not obtain transaction-synchronized Session for current thread

使用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,就可以了。