1 PackageCn.jbit.auction.dao;2 3 Importorg.hibernate.Session;4 Importorg.hibernate.SessionFactory;5 Importorg.hibernate.cfg.Configuration;6 7 Public classHibernateutil {8 //Initializes a Threadlocal object9 Private Static FinalThreadLocal Sessiontl =NewThreadLocal ();Ten Private Staticconfiguration configuration; One Private Final Staticsessionfactory sessionfactory; A Static { - Try { -Configuration =NewConfiguration (). Configure (); theSessionfactory =configuration.buildsessionfactory (); -}Catch(Throwable ex) { - Throw NewExceptionininitializererror (ex); - } + } - Public StaticSession currentsession () { + //The Get () method of the Sessiontl returns its corresponding thread internal variable according to the current thread . A //that is the session we need, the shared database connection is not secure in multi-threaded situations. at //threadlocal ensures that each thread has its own session. -Session session =(Session) sessiontl.get (); - //if session is NULL, a new session is opened - if(Session = =NULL) { - //Create a database connection object session. -Session =sessionfactory.opensession (); in //Save the database connection session to threadlocal. - Sessiontl.set (session); to } + //if the current thread has accessed the database, - //a Get () from Sessiontl can get the database connection object that the thread last fetched. the returnsession; * } $ /**Panax Notoginseng * Close Session - */ the Public Static voidclosesession () { +Session session =(Session) sessiontl.get (); ASessiontl.set (NULL); the session.close (); + } -}
Hibernateutil.java, used to open and close the session, can be reused in every project