Hibernate learning Notes (ii)

Source: Internet
Author: User

1.hibernate.cfg.xml Common Configuration
Hibernate.show_sql whether to output the Hibernate runtime SQL statements to the console with a value of true, False
Hibernate.format_sql whether the SQL statement output to the console is formatted with a value of true, False
Hbm2ddl.auto SQL statement Generation Policy, value Create, update, Create-dorp, validate
Hibernate.default_schema the default database
Hibernate.dialect the configuration database dialect, you can optimize the SQL statement.

Introduction to 2.Session Objects

Similar to JDBC connection, but Hibernate does not recommend using connection to connect to the database. is Hibernate execution process:

Session and connection are many-to-one relationships, and a connection can have multiple sessions. Session common methods are Sava (), update (), delete (), CreateQuery (),

3. Transaction transaction

Hibernate operations on the database are encapsulated in transaction, and are automatically submitted by default. You must commit the transaction to save the data. Automatic submission can be set through Session.dowork (), but it is not recommended!

@Test Public voidtestsavestudent () {Students s=NewStudents (1, "Zhang Sanfeng", "male",NewDate (), "Wudangshan"); Session.dowork (NewWork () {@Override Public voidExecute (Connection Connection)throwsSQLException {connection.setautocommit (true);        }                    });        Session.save (s); Session.flush ();//Be sure to have a refresh session for SQL to execute immediately}

4.Session explanation

There are two ways to get the session:

It is important to note in this diagram that using getcurrentsession () must be configured in the Hibernate.cfg.xml parameter!

The difference between getcurrentsession () and Opensession ()

1) getcurrentsession () automatically shuts down after a transaction commits or rolls back, while opensession () needs to be shut down manually, causing the database connection pool to overflow if not closed multiple times.

Test method: Testopensession (), Testgetcurrentsession ()

2) Getcurrentsession () is to get the existing session,opensession () to create a new session each time.

Test method: Testsavastudentwithopensession (), Testsavastudentwithgetcurrentsession (). See the following code:

Importjava.sql.Connection;Importjava.sql.SQLException;Importjava.util.Date;Importorg.hibernate.Session;Importorg.hibernate.SessionFactory;Importorg.hibernate.Transaction;Importorg.hibernate.cfg.Configuration;Importorg.hibernate.jdbc.Work;ImportOrg.hibernate.service.ServiceRegistry;ImportOrg.hibernate.service.ServiceRegistryBuilder;Importorg.junit.Test; Public classsessiontest {@Test Public voidtestopensession () {//Get parameter Configuration objectConfiguration config =NewConfiguration (). Configure (); //Get Service Registration ObjectServiceregistry Serviceregistry =NewServiceregistrybuilder (). Applysettings (Config.getproperties ()). Buildserviceregistry (); //Get Sessionfactory ObjectSessionfactory sessionfactory =config. buildsessionfactory (serviceregistry); //Session Object CreationSession session =sessionfactory.opensession (); Session Session2=sessionfactory.opensession (); if(Session = =Session2) System.out.println ("This is the same session object"); ElseSystem.out.println ("This is a different session object."); if(Session! =NULL) {System.out.println ("Session created successfully!" "); } Else{System.out.println ("Session creation failed!" "); }} @Test Public voidtestgetcurrentsession () {Configuration config=NewConfiguration (). Configure (); Serviceregistry Serviceregistry=NewServiceregistrybuilder (). Applysettings (Config.getproperties ()). Buildserviceregistry (); Sessionfactory sessionfactory=config. buildsessionfactory (serviceregistry); Session Session=sessionfactory.getcurrentsession (); Session Session2=sessionfactory.getcurrentsession (); SYSTEM.OUT.PRINTLN (Session==session2); if(Session! =NULL) {System.out.println ("Session created successfully!" "); } Else{System.out.println ("Session creation failed!" "); }} @Test Public voidtestsavastudentwithopensession () {Configuration config=NewConfiguration (). Configure (); Serviceregistry Serviceregistry=NewServiceregistrybuilder (). Applysettings (Config.getproperties ()). Buildserviceregistry (); Sessionfactory sessionfactory=config.buildsessionfactory (serviceregistry); Session Session1=sessionfactory.opensession (); Transaction Transaction=session1.begintransaction (); Students s=NewStudents (1, "Zhang Sanfeng", "male",NewDate (), "Wudangshan"); Session1.dowork (NewWork () {@Override Public voidExecute (Connection Connection)throwsSQLException {System.out.println ("Connection hashcode:" +Connection.hashcode ());        }                    });        Session1.save (s);                Transaction.commit (); Session Session2=sessionfactory.opensession (); Transaction=session2.begintransaction (); S=NewStudents (2, "Sun Yat-sen", "Male",NewDate (), "Hong Kong"); Session2.dowork (NewWork () {@Override Public voidExecute (Connection Connection)throwsSQLException {System.out.println ("Connection hashcode:" +Connection.hashcode ());        }                    });        Session2.save (s);    Transaction.commit (); } @Test Public voidtestsavastudentwithgetcurrentsession () {Configuration config=NewConfiguration (). Configure (); Serviceregistry Serviceregistry=NewServiceregistrybuilder (). Applysettings (Config.getproperties ()). Buildserviceregistry (); Sessionfactory sessionfactory=config.buildsessionfactory (serviceregistry); Session Session1=sessionfactory.getcurrentsession (); Transaction Transaction=session1.begintransaction (); Students s=NewStudents (1, "Zhang Sanfeng", "male",NewDate (), "Wudangshan"); Session1.dowork (NewWork () {@Override Public voidExecute (Connection Connection)throwsSQLException {System.out.println ("Connection hashcode:" +Connection.hashcode ());        }                    });        Session1.save (s);                Transaction.commit (); Session Session2=sessionfactory.getcurrentsession (); Transaction=session2.begintransaction (); S=NewStudents (2, "Sun Yat-sen", "Male",NewDate (), "Hong Kong"); Session2.dowork (NewWork () {@Override Public voidExecute (Connection Connection)throwsSQLException {System.out.println ("Connection hashcode:" +Connection.hashcode ());        }                    });        Session2.save (s);    Transaction.commit (); }}


5. Class configuration file Hbm.xml Common configuration: This address

http://www.imooc.com/video/7718

Hibernate learning Notes (ii)

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.