Hibernate is an open source Object Relational mapping framework that has a very lightweight object encapsulation for JDBC, making it possible for Java programmers to manipulate the database with arbitrary object programming thinking. Hibernate can be applied in any use of JDBC, either in Java client programs or in servlet/jsp Web applications, and, most of all, hibernate can replace CMP in an EJB-ee architecture, Complete the task of data persistence. There are 5 hibernate core interfaces, namely session, Sessionfactory, Transaction, query and configuration. These 5 hibernate core interfaces will be used in any development. Through these interfaces, not only can the persisted object be accessed, but also the transaction can be controlled.
Figure 1 Hierarchy of Hibernate core interfaces
Configuration interface
The function of the configuration interface is to configure the Hibernate and to start it. During hibernate startup, instances of the configuration class first locate the mapping document, read the configuration, and then create a Sessionfactory object.
Although the configuration interface plays only a small role in the entire Hibernate project, it is every object you encounter when you start hibernate.
A. property file (hibernate.properties): Configuration cfg = new Configuration (); XML file (hibernate.cfg.xml): Configuration cfg = new Configuration (). Configure (); B. Of course, you can also initialize the configuration file with a file object, so you don't need to have a hibernate.cfg.xml filename. The following code:
File File=new file ("D:/hibernamte2.cfg.xml");
Configuration Configure = new Configuration (). Configure (file);
C. Another, more commonly used, is to use the URL, the following code:
URL url = new URL (http://localhost/hibernate2.cfg.xml);
Configuration Configure = new Configuration (). Configure (URL); Important Method:
Public Configuration Configure (String Resource) throws hibernateexception; Specify the XML format configuration file to load in the parameter
Public Configuration Configure (URL url) thrwos hibernateexception:
Public Sessionfactory Buildsessionfactory () throws Hiberanteexcepiton: A new Sessionfactory object is instantiated from the configuration file. This sessionfactory will be immutable, so after creating the Sessionfactory object, all modifications made to the configuration object do not affect the Sessionfactory object that was previously created.
The purpose of the configuration object is to create a Sessionfactory object in addition to the ability to read the configuration file. Typically, an application creates a configuration object and then uses the configuration instance to establish a unique sessionfactory instance, which means that the configuration object exists only in the initialization phase of the system, All of the persistence operations can then be performed through this unique sessionfactory instance.
The configuration object needs to be created only when the hibernate is initialized, and when an instance of the Sessionfactory object is created using an instance of the configuration object, Its configuration information is already bound to the Sessionfactory object instance that he returned. Therefore, under normal circumstances, after getting the Sessionfactory object, the configuration object's mission is over.
Sessionfactory interface
Here we use a design pattern-factory mode, where the user program obtains the session instance from the factory class Sessionfactory.
Sessionfactory are not lightweight. The intent of its designers is to allow it to be shared throughout the application. Typically, a project usually requires only one sessionfactory, but when your project is working on multiple databases, you must specify a sessionfactory for each database.
A sessionfactory instance corresponds to a data storage source, and the application obtains the session instance from the Sessionfactory.
It has the following characteristics:
1 It is thread safe, which means that the same instance of it can be shared by each thread of the application.
2 It is heavyweight, which means that an instance of it cannot be created or destroyed at will. If the application accesses only one database, simply create a sessionfactory instance and create it when the application is initialized. If the application accesses multiple databases at the same time, you need to create a separate sessionfactory instance for each database.
3 later changes to the configuration object forces will not affect the already created Sessionfactory instance, if you need to use the sessionfactory based on the modified configuration instance, A new Sessionfactory instance needs to be recreated from the configuration object.
Sessionfactory is a heavyweight because it requires a large cache to hold predefined SQL statements and map meta data. Users can also configure a cache plug-in for Sessionfactory, which is called the second-level cache of Hibernate, which is used to store data that has been read by the work unit, and may be reused by other work units in the future. Therefore, the data in this cache can be shared by all units of work, and a unit of work usually corresponds to a database transaction.
The Sessionfactory interface is responsible for initializing hibernate.
Important Method:
Public Sessioin opensession () throws Hibernateexception: Creates a database connection and places it in the Session object and returns
Public session opensession (Connection Connection): Creates a Session object and places the Connection object that the parameter gives
public boolean isclosed (): Determines whether the current Sessionfactory object is closed
public void Close () throws Hibernateexception closes Sessionfactory and frees all sessionfactory-related resources (cache, database connection pool, etc.) but before calling this method, You should make sure that no session created by the current object is closed
Session interface
The session interface is one of the most important interfaces for hibernate developers. In hibernate, however, the instantiated session is a lightweight class that does not consume a lot of resources to create and destroy. This is really important in the actual project, because in the client program, the session object may be constantly created and destroyed, and if the session is too expensive, it will have a negative impact on the system. Session Features:
1) is not thread-safe, so when designing a software architecture, multiple threads should be prevented from sharing the same session instance;
2 The session instance is lightweight, so called lightweight, means that it does not need to consume too much resources to create and destroy. This means that session objects can be created and destroyed frequently in a program, such as assigning a separate session instance to each client request, or assigning a separate session instance to each unit of work.
3 The session has a cache, called the first level cache of Hibernate, which holds objects loaded by the current unit of work. Each session instance has its own cache, and the cache of this session instance can only be accessed by the current unit of work. The session interface is responsible for the crud operations of the persisted objects (the CRUD task is to communicate with the database, add, update, delete, load, and query objects, including many common SQL statements.) )。
In the minds of hibernate designers, they view the session as an intermediate interface between data connections and transaction management. We can think of the session as a buffer of persistent objects, hibernate can detect changes to these persistent objects and refresh the database in a timely manner. We sometimes call the session a persistent Layer manager because it contains some of the persistence-related operations, such as storing persisted objects to the database, and getting them from the database. Note that the Hibernate session is different from the httpsession in the JSP application. The Httpsesion object is later called the user session.
Important Method:
Public Transaction BeginTransaction () throws Hibernateexception: Returns a Transaction object that is associated with the current session object (means to restart a transaction in the database)
Public Transaction gettransaction (): Returns the Transaction object associated with the current session
Public Connection Connection Close () throws Hibernateexcepton: ending the current session object
public void Clear (): Empties the session, clears all entity objects that are saved in the current session cache, terminates all executing methods (Eg:save (), update (), delete () ...)
The public Serializable Save (object) throws hibernateexception the object specified by the current parameter (the system will first give the parameter object an identifier OID), which is equivalent to the INSERT statement Later in the detailed introduction
The public Connection Connection () throws Hibernateexception gets the Connection object contained in the current session.
Public Boolean contains (object): Determines whether the object (persisted Class) given by the parameter is in the cache of the current session
The public void evict (object) throws Hibernateexception: Removes the object given by the argument from the current session object class so that it changes from a persisted state to a free state. This state change does not cause synchronization of the database public Object load (Class theclass, Serializable ID) throws Hibernateexception returns the first argument In the table corresponding to the class, the second argument specifies the row (the second argument is the OID of the object to which the value of the primary key column in the table corresponds).
public void Update (object) throws Hibernateexception: Update an object into the database, later in detail
public void Delete (object) throws Hibernateexception: records that correspond to the objects specified by the parameter are deleted from the database
Public Object get (Class class,serializable ID) throws Hibernateexception: The same difference as the load () method is that if there is no corresponding record in the database table, get () method returns the Null,load () method to report an exception
Session session = Sessionfactory.opensession ();
Session session = Sessionfactory.getcurrentsession ();
Difference (important):
1, the call Getcurrentsession () will be from the context (thread or JTA) to find the session object, if there is an old, no new objects, opensession () Each call produces a new Session object.
2. The session created with Getcurrentsession () is bound to the current thread, and creating the Session object using Opensession () is not bound to the current thread.
3. The session created with Getcurrentsession () is automatically closed after the transaction ends and the opensession () must be closed manually.
With Getcurrentsession () you need to include the following configuration in the Hibernate.cfg.xml configuration file:
If it's a local thing, and JDBC a database:
<propety name= "Hibernate.current_session_context_class" >thread</propety>
If it is the global thing, and JTA things, multiple database resources or things resources:
<propety name= "Hibernate.current_session_context_class" >jta</propety>
Transaction interface
Transaction interface is an optional API, you can choose not to use this interface, replaced by the Hibernate's designer to write the underlying transaction code. It abstracts the application code from the underlying transaction implementation-this could be a JDBC transaction (connection transaction, a database based transaction), a JTA transaction (based on a distributed transaction, Managing transactions between multiple databases at the same time, or even a common object Request Broker Architecture (CORBA)-allows applications to control transaction boundaries through a consistent set of APIs. This helps maintain the portability of hibernate applications in different types of execution environments or containers.
Transaction tx = Session.begintransaction ();
Note: Call transaction (default: Autocommit=false) that must be displayed when using Hibernate for operation (add, delete, change).
Important Method:
The public void commit () throws Hibernateexception refreshes the current session and ends the transaction, which forces the database to commit the current transaction
public void rollback () throws Hibernateexception: Force rollback of current transaction
public boolean isactive () throws Hibernateexception: whether this transaction survives
Query and Criteria Interface
They are hibernate query interfaces for querying objects to the database, and for controlling the process of executing queries. The query instance encapsulates a HQL (Hibernate query Language) query statement, HQL is object-oriented, referencing the class name and the class's property name, not the table name and the table's field name. The criteria interface fully encapsulates query statements based on strings and is more object-oriented than the query interface, and the criteria interface is better at executing dynamic queries. The query interface gives you easy access to databases and persistent objects, and it can be expressed in two ways: the HQL language or the SQL statement for the local database. Queries are often used to bind query parameters, limit the number of query records, and ultimately perform query operations.
The criteria interface is very similar to the query interface, which allows you to create and execute object-oriented, standardized queries.
It is worth noting that the query interface is also lightweight and cannot be used outside of the session. The session interface's find () method also has the data query function, but it only executes some simple HQL query statement's shortcut method, its function is far without the query interface formidable.
Callback interface
When useful events occur-such as loading, storing, and deleting a persistent object-the callback interface notifies hibernate to receive a notification message. Generally speaking, the callback interface is not required in a user program, but it may be used when creating an audit log in a project.