"Hibernate Framework Learning": Hibernate advanced Hibernate Core interface and Class (i)

Source: Internet
Author: User
Tags commit connection pooling sessions

Let's take a look at Hibernate's execution process:

So we can probably know Hibernate's core interface and class, Hibernate's core class and interface a total of 6, namely: Session,

Sessionfactory, Transaction, Query, criteria, and configuration. These 6 core classes and interfaces will be used in any development. Wildcard

These interfaces allow access to persistent objects and transaction control. These 6 core interfaces and classes are described separately below. Configuration Class

The purpose of the configuration class is to configure Hibernate and start it. During Hibernate's start-up process,

An instance of the configuration class first locates the location of the mapped document, reads the configuration, and then creates a Sessionfactory object. Although

The Configuration class plays only a small role in the entire Hibernate project, but it is the first one that is encountered when starting hibernate

Like.

The configuration class is responsible for managing Hibernate config information. It includes the following content:

Hibernate run the underlying information: database URL, user name, password, JDBC driver class, database dialect, database connection pool, etc.

Hibernate mapping File (*.hbm.xml). Hibernate configuration in two ways:

Properties file (hibernate.properties).

Calling code:

Configuration Configure = new configuration ();

XML file (hibernate.cfg.xml).

Calling code:

Configuration Configure = new configuration (). Configure ();

Hibernate source code in the corresponding method:

The default call here is Hibernate.cfg.xml, if this hibernate core configuration name is not such a child, then you need to call:

XML file (hibernate3.cfg.xml)

Calling code:

Configuration Configure = new configuration (). Configure ("Hibernate3.cfg.xml");

Hibernate source code in the corresponding method:

Sessionfactory Interface

The Sessionfactory interface is responsible for initializing hibernate. It acts as a proxy for the data storage source and is responsible for creating session objects. It's used here.

Factory mode. Note that sessionfactory is not lightweight, because typically a project requires only one sessionfactory

Enough, you can specify a sessionfactory for each database when you need to manipulate multiple databases.

A session factory is a thread-safe, immutable cache snapshot of a mapped file that belongs to a single database. It is a session of the factory class that may hold a

An optional (level two) database cache that can hold data that can be reused in a transaction at the process level or at the cluster level.

The application obtains session (session) instances from the Sessionfactory (Session factory). It is shared among multiple application threads. Usual situation

, the entire application has only one session factory. For example, it is created when the app is initialized. However, if you use Hibernate to access multiple data

Library, you need to use a session factory for each database. The session factory caches the generated SQL statements and the mapping elements that Hibernate uses at run time

Data.

Calling code:

Sessionfactory sessionfactory = Configure.buildsessionfactory ();

Hibernate source code in the corresponding method:

Description: Sessionfactory is created by the configuration object, so each hibernate configuration file is actually for Sessionfactory

The configuration. Session Interface

The session interface is responsible for performing crud operations on persisted objects (the task of crud is to complete the communication with the database, including many common SQL language

Sentence). However, it is important to note that the session object is non-thread-safe. At the same time, Hibernate's session differs from the HttpSession in JSP applications. This

When using the term session, in fact refers to hibernate in the session, and later will be HttpSession object called the user session.

For the session we are so familiar with, in the Javaweb development session can be used to save the user session state information. and

The session in Hibernate is the object-to-database session Persistence Manager.

A session is a single-threaded, short-lived object that represents a conversation between an application and a persistence layer, encapsulating the engineering of a JDBC connection, a transaction. Save Required

The object cache needs to be persisted, used to traverse the object graph, or to represent a Lookup object.

Session is not thread-safe, it represents a single operation with the database, and its concept is between connection and transaction

Room The session is also known as the persistence Manager because it is a persistence-related operation interface. Session opened through Sessionfactory, in all the

After the work is completed, you need to close it. It has no relation to the httpsession of the web layer.

We do not recommend using the JDBC Connection operation database, but using the session to manipulate the database, so the session can be understood as

As the database object.

Session and connection, is a many-to-one relationship, each session has a corresponding connection, a connection not at the same time

Can be used by more than one session. How to get the Session object

1) The first method of calling code:

Sessionfactory.opensession ();

Hibernate source code in the corresponding method:

The second way to invoke the code:

Sessionfactory.getcurrentsession ();

Hibernate source code in the corresponding method:

If using getcurrentsession () requires a certain configuration in the Hibernate.cfg.xml file, if it is a local transaction (JDBC transaction),

Set to: <property name= "Hibernate.current_session_context_class" >thread</property>;

If it is a global transaction (JTA transaction), it is configured as: <property name= "Hibernate.current_session_context_class" >jta</property>

Let's look at an example:

Package com.demo.test;
Import java.sql.Connection;
Import java.sql.SQLException;

Import Java.util.Date;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.Transaction;
Import org.hibernate.cfg.Configuration;
Import Org.hibernate.jdbc.Work;
Import Org.hibernate.service.ServiceRegistry;
Import Org.hibernate.service.ServiceRegistryBuilder;

Import Org.junit.Test;

Import com.demo.domain.Students; public class Sessiontest {@Test public void testopensession () {//Create config Object configuration config =new Configurati
        On (). Configure (); Create a Service Registration object Serviceregistry serviceregitry=new serviceregistrybuilder (). Applysettings (Config.getproperties ()). Buil
        Dserviceregistry ();
        Create a session Factory object Sessionfactory sessionfactory =config.buildsessionfactory (serviceregitry);        
 
        Conversation object Session Sessions session =sessionfactory.opensession (); if (session! = NULL) {System.out.println ("use Opensession to create session successfully.
		"); } else {
			System.out.println ("failed to create session using Opensession.
		");
        } Session sessioncopy =sessionfactory.opensession ();
		SYSTEM.OUT.PRINTLN (Session = = sessioncopy);//output False to indicate that it is not the same session} @Test public void Testgetcurrentsession () {
        Create a Configuration object, default read config file configuration config =new configuration (). Configure (); Create a Service Registration object Serviceregistry serviceregitry=new serviceregistrybuilder (). Applysettings (Config.getproperties ()). Buil
        Dserviceregistry ();
        Create a session Factory object Sessionfactory sessionfactory =config.buildsessionfactory (serviceregitry);
        
        Conversation object Session Sessions session =sessionfactory.getcurrentsession (); if (session! = NULL) {System.out.println ("use Getcurrentsession to create session successfully.
		"); } else {System.out.println ("failed to create session using Getcurrentsession.
		");
        } Session sessioncopy =sessionfactory.getcurrentsession ();
	SYSTEM.OUT.PRINTLN (Session = = sessioncopy);//Output True indicates the same session}
} 

Console output:


Continue to add code in the test class above:

Package com.demo.test;
Import java.sql.Connection;
Import java.sql.SQLException;

Import Java.util.Date;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.Transaction;
Import org.hibernate.cfg.Configuration;
Import Org.hibernate.jdbc.Work;
Import Org.hibernate.service.ServiceRegistry;
Import Org.hibernate.service.ServiceRegistryBuilder;

Import Org.junit.Test;

Import com.demo.domain.Students; public class Sessiontest {@Test public void testsavestudentsopensession () {//Create configuration object, default read config file
        Config =new Configuration (). Configure (); Create a Service Registration object Serviceregistry serviceregitry=new serviceregistrybuilder (). Applysettings (Config.getproperties ()). Buil
        Dserviceregistry ();
        Create a session Factory object Sessionfactory sessionfactory =config.buildsessionfactory (serviceregitry);
        Conversation object Session Sessions session =sessionfactory.opensession ();
   Open transaction Transaction Transaction = Session.begintransaction ();     
        Students student = new Students (4, "Lao Zhang", "Male", New Date (), "Beijing"); Session.dowork (new work () {@Override public void execute (Connection Connection) throws SQLException {Syste
			M.OUT.PRINTLN ("Connection hashcode:" + connection.hashcode ());
        }
		});
        Session.save (student);
        
        Session.close ();//Here we do not close session transaction.commit ();
        Session sessioncopy = Sessionfactory.opensession ();
        Transaction = Sessioncopy.begintransaction ();
        Student = new Students (5, "Lao Li", "male", New Date (), "Tianjin"); Sessioncopy.dowork (new work () {@Override public void execute (Connection Connection) throws SQLException {S
			YSTEM.OUT.PRINTLN ("Connection hashcode:" + connection.hashcode ());

        }
		});
        Sessioncopy.save (student);
           
	Transaction.commit (); } @Test public void Testsavestudentsgetcurrentsession () {//Create configuration object, default read configuration file config =new Configu Ration (). confiGure (); Create a Service Registration object Serviceregistry serviceregitry=new serviceregistrybuilder (). Applysettings (Config.getproperties ()). Buil
        Dserviceregistry ();
        Create a session Factory object Sessionfactory sessionfactory =config.buildsessionfactory (serviceregitry);
        Conversation object Session Sessions session =sessionfactory.getcurrentsession ();
        
        Open transaction Transaction Transaction = Session.begintransaction ();
        Students student = new Students (6, "Zhao Liu", "male", New Date (), "Beijing"); Session.dowork (new work () {@Override public void execute (Connection Connection) throws SQLException {Syste
			M.OUT.PRINTLN ("Connection hashcode:" + connection.hashcode ());
        }
		});
        Session.save (student);
        Session.close ();
        
        Transaction.commit ();
        Session sessioncopy = Sessionfactory.getcurrentsession ();
        Transaction = Sessioncopy.begintransaction ();
        Student = new Students (7, "Zhou Seven", "Male", New Date (), "Tianjin"); Sessioncopy.DoWork (new work () {@Override public void execute (Connection Connection) throws SQLException {SYSTEM.OUT.PR
			INTLN ("Connection hashcode:" + connection.hashcode ());

        }
		});
        Sessioncopy.save (student);
           
	Transaction.commit (); }
	
}

Run the Testsavestudentsopensession () test method:

Console output:

Run the Testsavestudentsgetcurrentsession () test method:

Console output:

From the above example, we see the difference between Opensession and getcurrentsession:

(1) Opensession each time a new session object is created, Getcurrentsession uses the existing session object. Opensession each time

Use is to open a new session, use up the need to call the Close method closed session;getcurrentsession is to get the current session of the

Like, continuous use multiple times, the resulting session is the same object, which is one of the differences with opensession;

Generally in the actual development, often use getcurrentsession, because the general is to deal with the same transaction, so under normal circumstances relatively less use

Opensession.

(2) Getcurrentsession automatically shuts down after a transaction is committed or rolled back, and opensesssion requires you to shut down manually if you use

Opensession instead of manually shutting down, multiple times will cause connection pooling to overflow. Opensession there is a thread concurrency problem, and getcurrentsession

The way to get the session, a user to get the session will automatically bind a thread until the current session expires, Hibernater will thread stripping will

To ensure the uniqueness of each user's operational data. Transaction Interface

Transaction interface is an optional API, you can choose not to use this interface, instead of the hibernate designers write their own bottom

The transaction-processing code. The transaction interface is an abstraction of the actual transaction implementation, including the JDBC transaction, the JTA

UserTransaction, or even a CORBA transaction. This design is designed to enable developers to use a unified transaction interface, so that

Their projects can be easily ported between different environments and containers.

The transaction interface is single-threaded, and the application uses it to represent a batch of indivisible operations. A session may span multiple things in some cases

Works
The Transaction (transaction) abstracts the application code from the underlying transaction implementation, which could be a JDBC transaction, a JTA user transaction, or

is even a public object request broker structure (CORBA) that allows applications to control transaction boundaries through a consistent set of APIs. This helps to keep

Hibernate applies portability in different types of execution environments or containers.
Calling code:

Transaction transation = Session.begintransaction ();

Hibernate source code in the corresponding method:


Description: When working with Hibernate, you must explicitly call transaction (default: Autocommit=false).
Hibernate operations on data are encapsulated in transactions, and the default is non-autocommit. So when the session is saving the object, if you do not

When you open a transaction and commit the transaction manually, the object is not actually saved in the database.

Let's look at an example:

Package com.demo.test;

Import Java.util.Date;
Import org.hibernate.Session;
Import Org.hibernate.SessionFactory;
Import org.hibernate.Transaction;
Import org.hibernate.cfg.Configuration;
Import Org.hibernate.service.ServiceRegistry;
Import Org.hibernate.service.ServiceRegistryBuilder;
Import Org.junit.After;
Import Org.junit.Before;

Import Org.junit.Test;

Import com.demo.domain.Students;
	public class Teststudents {private Sessionfactory sessionfactory;
	Private session session;
	
	Private Transaction Transaction;
        @Before public void init () {//Create config Object configuration Config =new configuration (). Configure (); Create a Service Registration object Serviceregistry serviceregitry=new serviceregistrybuilder (). Applysettings (Config.getproperties ()). Buil
        Dserviceregistry ();
        Create a session Factory object Sessionfactory =config.buildsessionfactory (serviceregitry);
        Conversation Object session =sessionfactory.opensession ();
   Open transaction//transaction = Session.begintransaction ();     
	} @Test public void Teststudents () {Students s =new Students (3, "Harry", "Male", new Date
            (), "Beijing"); 
    	Session.save (s);//Save object into database} @After public void Destory () {//transaction.commit ();//COMMIT Transaction Session.close ();//Close session sessionfactory.close ();//Close Session Factory}}

The console has no output, and of course there is no corresponding sid=3 data in the database. This is because the object cannot be saved without opening the transaction

In the database. The main thing is that hibernate does not automatically commit transactions by default.

The database displays:

If you want hibernate to commit the transaction automatically like JDBC, you must call the DoWork () method of the session object to get the JDBC

After connection, it is set to autocommit transaction mode (usually not recommended). The DoWork method is not available for JDBC connection

Of
We modify the above test code:

    @Test public
    void Teststudents () {             
            Students s =new Students (3, "Harry", "Male", New Date (), "Beijing");
            Session.dowork (new work () {

            	   @Override public
            	   void execute (Connection Connection) throws sqlexception{
            	       Connection.setautocommit (True);
            	   }

            	});

            	Session.save (s);//Save object into Database 
            	Session.flush ();//TRUE output SQL statement          
    }

Console output:

The database displays the results:

Hibernate is used to manipulate the database using the session, while DoWork uses the JDBC Connection object to perform the native

SQL statements, so there's no point in using Hibernate.


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.