The new thread needs to bind the hibernate session. Ability to use transactions and delay loading functions in new threads, otherwise the no session exception will be exposed.
The workaround:
New Runnable () { @Override public void Run () {// ----------binding session to the current thread------------ Sessionfactory sessionfactory = (sessionfactory) applicationcontext.getbean ("Sessionfactory"); Boolean participate = Concurrentutil.bindhibernatesessiontothread (sessionfactory);// --------- Your business---------------<pre name= "code" class= "java" >// ----------Close Session------------ Concurrentutil.closehibernatesessionfromthread (participate, sessionfactory); } }
Bindhibernatesessiontothread Method:
public static Boolean Bindhibernatesessiontothread (Sessionfactory sessionfactory) { if ( Transactionsynchronizationmanager.hasresource (sessionfactory)) { //Do not modify the Session:just set the Participate flag. return true; } else { Session session = Sessionfactory.opensession (); Session.setflushmode (flushmode.manual); Sessionholder Sessionholder = new Sessionholder (session); Transactionsynchronizationmanager.bindresource (Sessionfactory, Sessionholder); } return false; }
Closehibernatesessionfromthread method
public static void Closehibernatesessionfromthread (Boolean participate, Object sessionfactory) { if (!participate) { Sessionholder Sessionholder = (sessionholder) Transactionsynchronizationmanager.unbindresource ( Sessionfactory); Sessionfactoryutils.closesession (Sessionholder.getsession ()); } }
Transaction boundaries are controlled by AOP or transactional tags. The demo sample code is just a guarantee that a transactional method can get the session object from the current thread when needed.
Most of the above code is captured from spring's opensessioninviewfilter.
Service end new multi-threaded use hibernatesession Eliminate no session