Note that Sessionfactory is designed to be thread-safe (Thread-safe) in Hibernate, but unfortunately the session is not thread safe.
This means that it is possible for multiple threads to share and manipulate the same session, which can easily confuse data.
The solution is as follows: (in fact, Hibernate's documentation has been mentioned earlier)
New Hibernateutil class:
1.import Org.apache.commons.logging.Log;
2.import org.apache.commons.logging.LogFactory;
3.import org.hibernate.*;
4.import org.hibernate.cfg.*;
5.
6.public class Hibernateutil {
7. private static log log = Logfactory.getlog (Hibernateutil.class);
8. Private static final sessionfactory sessionfactory;
9.10. static {
One. try {
//Create the Sessionfactory 13. Sessionfactory = new Configuration (). Configure ()
Buildsessionfactory ();
A catch (Throwable ex) {
//Make sure your log the exception, as it might be swallowed 17. Log.error ("Initial sessionfactory creation failed.", ex);
throw new Exceptionininitializererror (ex);
19.}
20.}
21.22. public static final ThreadLocal session = new ThreadLocal ();
23.24. public static session currentsession () {
Session S = (session) Session.get ();
26.27. Open a new session, if this Thread has none yet 28. if (s = = null) {
s = sessionfactory.opensession ();
Session.set (s);
31.}
32.33. return s;
34.}
35.36. public static void CloseSession () {
Session S = (session) Session.get ();
38.39. if (s!= null) {
S.close ();
41.}
42.43. Session.set (NULL);
44.}
45.}