Hibernateutil.java, used to open and close the session, can be reused in every project

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.