Load or delay load must be connected to the database, while in Java to connect to the database is dependent on Java.sql.Connection, in Hibernate session is the Connection layer of high-level package, A session corresponds to a connection, and it is necessary to have a session to implement lazy loading. And to delay loading, you have to be sure the same session. It is not possible to delay loading the proxy object of the previous session with another session. We all know that connection must be closed after use, so how do we ensure that an HTTP request is always using a session? That's a connection. Also, make sure that HTTP requests are closed correctly after they are terminated.
Okay, now that we know the problem we're going to solve,
1. How to ensure that the session is closed correctly after the HTTP request ends
2. How to ensure that the same session is used throughout the HTTP request
Packageutil;Importjava.io.Serializable;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.cfg.Configuration; Public classHibernatesessionfactoryImplementsserializable{Private Static FinalString config_file_location = "/hibernate.cfg.xml"; Private Static FinalThreadlocal<session> ThreadLocal =NewThreadlocal<session>(); Private StaticConfiguration Configuration =NewConfiguration (); Private StaticSessionfactory sessionfactory=NULL; Private StaticString ConfigFile =config_file_location; //The static code block only executes once when the class is instantiated Static{ Try{configuration.configure (configfile); Sessionfactory=configuration.buildsessionfactory (); } Catch(Exception e) {System.err.println ("%%%% Error Creating sessionfactory%%%%"); E.printstacktrace (); } } //Get Session Public Staticsession Getcurrentsession () {Session session=Threadlocal.get (); //determines whether the session is empty, if empty, creates a session and pays the thread variable tlocalsess Try { if(Session = =NULL&&!Session.isopen ()) { if(sessionfactory==NULL) {rbuildsessionfactory (); }Else{Session=sessionfactory.opensession (); } //session = (sessionfactory! = null)? Sessionfactory.opensession (): null;} threadlocal.set (session); } Catch(Exception e) {//Todo:handle Exception } returnsession; } Public Static voidrbuildsessionfactory () {Try{configuration.configure (configfile); Sessionfactory=configuration.buildsessionfactory (); } Catch(Exception e) {System.err.println ("%%%% Error Creating sessionfactory%%%%"); E.printstacktrace (); } }}
Hibernatesessionfactory Setup-use threadlocal