Importorg.hibernate.HibernateException; Importorg.hibernate.Session; Importorg.hibernate.SessionFactory; Importorg.hibernate.cfg.Configuration; Public classHibernateutil {Private StaticSessionfactory sessionfactory =NULL; Static { Try{Configuration cfg=NewConfiguration (). Configure (); Sessionfactory=cfg.buildsessionfactory (); } Catch(hibernateexception e) {//Todo:handle ExceptionE.printstacktrace (); } } Public Staticsessionfactory getsessionfactory () {returnsessionfactory; } Public Staticsession getsession () {Session session= (Sessionfactory! =NULL) ? Sessionfactory.opensession ():NULL; returnsession; } Public Static voidClosefactory (Session session) {if(Session! =NULL) { if(Session.isopen ()) {session.close (); } } } }
1. This tool class can be used directly to get the session (static method) but it is important to note that this class is not thread-safe. Hibernate advocates thread-safe tool classes
2. The specific process can be understood to get the configuration object---> Get session factory sessionfactory---> Get session opensession (); The final call to the session of the various methods for data manipulation.
3. You can refer to the hibernate documentation for a very detailed introduction to the HIBERNATE-DISTRIBUTION-3.3.2.GA\DOCUMENTATION\MANUAL\ZH-CN Chinese version under the document folder
Document content
1.1.6. Startup and Helper Classes
It is time-to-load and store Some event
objects, but first The setup with some infrastructure code. You have the to-startup Hibernate by building a global org.hibernate.sessionfactory
object and storing it somewhere for easy access in application code. A org.hibernate.sessionfactory
is used to Obtain org.hibernate.session
instances. A org.hibernate.session
represents a single-threaded unit of work. The org.hibernate.sessionfactory
is a Thread-safe global object that is instantiated once.
We'll create a HibernateUtil
helper class that takes care of the startup and makes accessing the more org.hibernate.SessionFactory
convenient.
PackageOrg.hibernate.tutorial.util; Importorg.hibernate.SessionFactory; Importorg.hibernate.cfg.Configuration; Public classHibernateutil {Private Static FinalSessionfactory sessionfactory =buildsessionfactory (); Private Staticsessionfactory buildsessionfactory () {Try { //Create the sessionfactory from Hibernate.cfg.xml return NewConfiguration (). Configure (). Buildsessionfactory (); } Catch(Throwable ex) {//Make sure your log the exception, as it might be swallowedSystem.err.println ("Initial sessionfactory creation failed." +ex); Throw NewExceptionininitializererror (ex); } } Public Staticsessionfactory getsessionfactory () {returnsessionfactory; } }