Purpose of Sessionfactory: Create session, maintain database connection pool
The sessionfactory in the test file creates a database connection, so sessionfactory generates a database connection pool from the configuration information in the configuration file, from which a database connection is taken out.
Sessionfactory = new Annotationconfiguration (). Configure (). Buildsessionfactory ();
Configure is used to invoke database information, configure () can specify Hibernate.cfg.xml name
Create a session with Getcurrentsession:
@Testpublic void Testteachersave () {Teacher t = new Teacher (); T.setname ("T1"); T.settitle ("Middle"); T.setbirthdate (new Date ());//session Session = Sessionfactory.opensession (); Session session = Sessionfactory.getcurrentsession (); Session.begintransaction (); Session.save (t); Session Session2 = Sessionfactory.getcurrentsession (); SYSTEM.OUT.PRINTLN (Session = = Session2); Session.gettransaction (). commit (); Session Session3 = Sessionfactory.getcurrentsession (); SYSTEM.OUT.PRINTLN (Session = = Session3);}
Opensession () is always creating a new session, this session needs close, and getcurrentsession () if the environment has a session to take the environment, do not need close.
Hibernate--coreapi--configuration sessionfactory--getcurrentsession--opensession