Hibernate the core Components
In Java Web applications based on MVC design patterns, hibernate can be used as the model layer/data access layer. It maps a Java object or PO (persistent object, persisted object) to a database in a database through a configuration file (Hibernate.properties or Hibernate.cfg.xml) and a mapping file (***.hbm.xml) , and then through the operation of PO, the data in the table to increase, delete, change, check and other operations.
In addition to configuration files, mapping files, and persistence classes, the core components of hibernate include the following sections:
a) configuration class : Used to read Hibernate configuration files and generate Sessionfactory objects.
b) sessionfactory interface : Sessionfactory is responsible for creating the session instance. Can be created from a configuration instance
c) Session interface : Used to operate the PO. It has methods such as get (), load (), save (), update (), and delete () to load, save, update, and delete the PO. It is the core interface of hibernate.
d) Query interface : Used for querying the PO. It can be generated from the CreateQuery () method of the session.
e) Transaction interface : Used to manage hibernate transactions, its main methods are commit () and rollback (), which can be generated from the session's Begintrancation () method.
Persistent Object
Persistent objects can be normal JavaBeans, and the only special thing is that they are associated with (just one) session. There are three states of JavaBeans in Hibernate:
1. temporary status (transient): When an JavaBean object is isolated in memory and does not have any association with the data in the database, the JavaBeans object is called a temporary object (transient Object).
2. Persistent State (persistent): When a JavaBean object is associated with a session, it becomes persisted (persistent object)
3. off-State (detached): While this session is closed, this object will also be out of the persistence state and become a de-detachedobject, which can be freely used by any layer of the application. For example, you can do data transferobject that deal with the presentation layer.
Hibernate the running Process
Hibernate The following are the operating procedures:
1. Through the configuration (). Configure (); Read and parse the Hibernate.cfg.xml config file
2. Read and parse mapping information by <mappingresource= "Com/xx/user.hbm.xml"/> in Hibernate.cfg.xml
3. Through Config.buildsessionfactory ();//Create Sessionfactory
4.sessionfactory.opensession ();//Open Sesssion
5.session.begintransaction ();//Create Transaction Transation
6.persistentoperate Persistent operation
7.session.gettransaction (). commit ();//COMMIT Transaction
8. Close session
9. Close Sesstionfactory
Strung up and said:
A: The application first calls the Configration class, which reads the information from the Hibernate configuration file and the mapping file and uses this information to generate a Sessionfactory object.
B: Then a Session object is generated from the Sessionfactory object, and the transaction object is generated with the session object; Get (), load (), save (), update (), delete (), and saveorupdate () to load, save, update, delete, and so on; in the case of a query, a query object can be generated from the session object and then executed with the Queries object, and if there is no exception, The transaction object submits the results of these operations to the database.
Shown in diagram:
Why to use:
1. The code for JDBC access to the database is encapsulated, which greatly simplifies the tedious repetitive code of the data access layer.
2.Hibernate is a mainstream, JDBC-based persistence framework that is an excellent ORM implementation. He simplifies the coding of the DAO layer to a great extent
3.hibernate uses the Java reflection mechanism rather than the bytecode enhancer to achieve transparency.
The performance of 4.hibernate is very good because it is a lightweight framework. The flexibility of the mapping is excellent. It supports a variety of relational databases, from one-to-one to many-to-many complex relationships.
Some explanations for the core components:
1. The Congifuration object generates a Sessionfactory object based on the current configuration information. Once the Sessionfactory object is constructed, specific configuration information is given, that is, subsequent configuration changes do not affect the created Sessionfactory object. If you want to assign the configuration information after clog to the Sessionfactory object, you need to generate the Sessionfactory object from the new configuration object.
Sessionfactory is pure and safe, can be called by multithreading to get the session, and the construction of sessionfactory is very resource-intensive, so in most cases an application only initializes a sessionfactory, Provides a session for different threads.
2.Session is a session between the application and the database, the center of Hibernate operation, the basis of the persistence layer operation, equivalent to the connection in JDBC. The session object was created by Sessionfactory:
Session session = Sessionfactory.opensession ();
There is no difference between a persistent class and a normal JavaBean, but it has the ability to persist after it is associated with the session. Of course, this persistence is controlled by the session, that is, by loading the session object, saving, creating, or querying the persisted object. Session Class of Save (), delete () and load () and other methods to complete the persistence of the object, such as saving, delete, modify loading operations! The use of the session class method can be divided into the following five categories:
A: Get persisted objects: get () and load () methods.
B: Persist object's save, update and Delete methods such as Save (,), Update () Saveorupdate (), and delete ().
C:createquery () Method: The Query object that is used to generate from the session.
D:begintransaction () Method: Generates a transaction object from the Session object.
E: Methods for managing the session: IsOpen (), flush (), clear (), evict (), and Close (), where the IsOpen () method is used to check if the session is still open; flush () is used to clean up the session cache. and send out the SQL statements in the cache, clear () clears all cache objects in the session evict () method to clear the session cache of an object; Close () closes the session.
Comparison of 3.get and load methods:
The Get () method executes in the following order:
A): First find the object through the ID in the session cache, if there is an object of this ID, return it directly
b): Look in the level two cache and return it when found.
c): If this object is not found in the session cache and level two cache, the object with this ID is loaded from the database
Therefore, the get () method does not always cause SQL statements, and only sends sql! to the database if there is no data in the cache.
Load with Get () The difference:
A: When you load an object immediately (when hibernate takes data from the database to assemble an object immediately after it has been assembled from the database), if the object exists, the load () and the Get () method do not differ, you can get the initialized object; However, if the object does not exist and is loaded immediately, using the Get () method returns null, and using load () throws an exception. So when using the load () method, confirm that the primary key ID of the query must be present, from this point it is not easy to get!
B: Delay loading the object (Hibernate gets the data from the database assemble an object, the objects associated with the object are not immediately taken from the database, but wait until needed to assemble the object associated with the object from the database), get () The method still sends the SQL statement using an immediate load and obtains the initialized object, and the load () method does not send the SQL statement at all, it returns a proxy object that is initialized only when the object is accessed.
4.Trancation interface
This interface allows you to apply equate to define the unit of work, while also invoking JTA or JDBC to perform the thing management. Its operation is related to the session interface, and the BeginTransaction () method of the session can be called to generate an transaction instance.
A session instance can be associated with more than one transaction instance, but a particular session instance must be associated with at least one uncommitted transaction instance at any time.
Transaction interfaces are commonly used in the following ways:
A:commit (); commits the associated session instance.
B:rollback (); undo a thing operation.
C:wascommitted (); whether things are committed.
At the end of this article, we introduce the Hibernateutil class
The Hibernateutil class is a widely used program for Hibernate session management. It is an auxiliary class for session management established using the Threadlocal class. The use of threadlocal can effectively isolate the data used for execution, so it avoids the problem of data sharing between threads in the session.
Simple analysis of hibernate working principle