1. Add the following code to the Hibernate.cfg.xml file to turn on thread safety:
<property name= "Hibernate.current_session_context_class" >thread</property>
Specific as follows:
<!DOCTYPE hibernate-configuration Public "-//hibernate/hibernate configuration DTD 3.0//en" "Http://www.hibernate. Org/dtd/hibernate-configuration-3.0.dtd "><hibernate-configuration> <session-factory> < Propertyname= "Hibernate.dialect">Org.hibernate.dialect.MySQL5InnoDBDialect</ Property> < Propertyname= "Hibernate.connection.driver_class">Com.mysql.jdbc.Driver</ Property> < Propertyname= "Hibernate.connection.url">Jdbc:mysql:///hibernate</ Property> < Propertyname= "Hibernate.connection.username">Root</ Property> < Propertyname= "Hibernate.connection.password">123456</ Property> < Propertyname= "Hibernate.hbm2ddl.auto">Update</ Property> < Propertyname= "Hibernate.show_sql">True</ Property> < Propertyname= "Hibernate.current_session_context_class">Thread</ Property> <MappingResource= "Learn\hibernate\bean\person.hbm.xml"/> </session-factory></hibernate-configuration>
2. Test:
Packagelearn.hibernate.test;Import Staticorg.junit.assert.*;ImportLearn.hibernate.bean.Person;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.Transaction;Importorg.hibernate.cfg.Configuration;ImportOrg.hibernate.service.ServiceRegistry;ImportOrg.hibernate.service.ServiceRegistryBuilder;ImportOrg.junit.After;ImportOrg.junit.Before;Importorg.junit.Test; Public classtesthibernate {sessionfactory Factory=NULL; Session Session=NULL; Transaction TX=NULL; /*** Initialize data before testing *@throwsException*/@SuppressWarnings ("Deprecation") @Before Public voidSetUp ()throwsException {System.out.println ("---------Initialize Data----------"); Configuration Config=NewConfiguration (). Configure (); Serviceregistry SR=NewServiceregistrybuilder (). Applysettings (Config.getproperties ()). Buildserviceregistry (); Factory=Config.buildsessionfactory (SR); //session = Factory.opensession (); //get a thread-safe session for use in a multithreaded environmentSession =factory.getcurrentsession (); } /*** Release (destroy) data after testing *@throwsException*/@After Public voidTearDown ()throwsException {System.out.println ("---------Release Data----------"); //get a thread-safe session, do not need to program the shutdown, the transaction will automatically close after the commit /*if (Session.isopen ()) {session.close (); }*/ } /*** Bulk Write Data*/@Test Public voidTestadd () {TX=session.begintransaction (); Person Person=NewPerson ("admin", 22, 123456,NULL); Session.persist (person); Tx.commit (); } @Test Public voidTestget () {//If you get a thread-safe session, open the transactiontx =session.begintransaction (); Person P= (person) session.get (person).class, 12); SYSTEM.OUT.PRINTLN (P); Tx.commit (); }}
Hibernate Learning---section 14th: Hibernate session Thread Safety