[R] Hibernate


Hibernate is an open source object-relational mapping framework, it very lightweight JDBC object package so that Java programmers can use arbitrary object-oriented programming thinking to manipulate the database. Hibernate can be applied to any occasions using JDBC, either in the Java client program can also be used in the Servlet / JSP Web application, most revolutionary, Hibernate can replace the CMP in the application EJB J2EE architecture completion of data persistence task.

Introduction to the core interface

Hibernate core interface, a total of five, namely: the Session, SessionFactory, Transaction, Query and Configuration. The five core interfaces are used in any development. These interfaces can not only access to persistent objects, but also to transaction control. Following these five core interfaces were to be introduced.

Session interface is responsible for the implementation of persistent object CRUD operations (CRUD task is to complete the communication with the database contains a lot of common SQL statements). Note that Session is not thread safe. Hibernate session is different from the HttpSession in JSP applications. When the term of the session, in fact, refers to the Hibernate session, after will HttpSesion object called a user session.

SessionFactory interface:

SessionFactory interface is responsible for the initialization Hibernate. It acts as a source of data storage agent, and is responsible for creating the Session object. Here used in the factory pattern. Note that SessionFactory is not lightweight, because under normal circumstances, a project usually need only a SessionFactory enough, when the need to operate more than one database can be specified for each database a the SessionFactory.

Configuration interface:

Configuration interface is responsible for configuration and startup Hibernate to create a SessionFactory object. In the the Hibernate startup process, the Configuration instance of the class first position to map the location of the document, read the configuration, and then create the SessionFactory object.

Transaction interface:

Transaction interface is responsible for affairs related operations. It is optional, developers can design and write your own underlying transaction code.

ยท Query and Criteria Interface: Query and Criteria interface is responsible to perform a variety of database queries. It can be used either expression of the the HQL language or SQL statement.

Hibernate primary key


Assigned by the user-generated primary key value, and to specify an exception is thrown before save ()

Features: the generation of the primary key value is completely determined by the user, regardless of the underlying database. Users need to maintain the primary key value in the before calling session.save () to specify the primary key value.


Hilo high and low bit algorithm to generate the primary key, high and low bit algorithm uses a high value and a low value, and then the two values ??obtained by the algorithm stitching together as only the primary key in the database. Hilo requires additional database tables and fields to provide high value source. Please state by default table

hibernate_unique_key default field called next_hi. next_hi must have a record otherwise an error occurs.

Features: the need for additional support of the database table, can guarantee the same database primary key only, but can not guarantee the uniqueness of the primary key between multiple databases. The the Hilo primary key generated by Hibernate maintenance, Hilo has nothing to do with the underlying database, but should not manually modify the hi / lo algorithm to use the value of the table, otherwise it will cause duplicate primary key exception.


Increment primary key value automatically growth to generate a new primary key value, but requires that the underlying database supports Sequence. Such as Oracle, DB2, and so on. Need to mapping file xxx.hbm.xml, joined Increment identifiers settings.

Features: Hibernate maintenance, suitable for all database is not suitable for the more complicated process to update the database, suitable for a single process to access the database. Can not be used in a clustered environment.


Identity was based on the underlying database to support growth in different databases with different primary key growth mode.

The Features: associated with the underlying database, database support IDENTITY, such as MySQL is AUTO_INCREMENT in SQL Server is Identity supported database MySQL, SQL Server, DB2, Sybase and HypersonicSQL or. Identity without the Hibernate user intervention, more convenient to use, but not easy to transplant procedures between different databases.


Sequence Sequence mode requires that the underlying database support, such as Oracle Database

Features: need support serialization of the underlying database, DB2, PostgreSql, Qracle, SAPDb between different databases transplant program in support of the sequence database, especially from the sequence database support transplanted to the database does not support serialization need to modify the configuration file


Native primary key generated based on different underlying database primary key generated automatically selects Identity, Sequence, Hilo

Features: Depending on the underlying database using different primary key generation methods. Hibernate will use different mapping based on the underlying database, thus facilitating the transplant procedure, the project If more than one database, you can use this way.


UUID using 128-bit UUID algorithm to generate the primary key to ensure that the primary key in the network environment only, will be able to guarantee the uniqueness of the primary key in the different databases and different servers.

Features; to ensure that the primary key in the database only to generate the primary key of take up more storage space

Foreign GUID

Foreign for one-to-one relationship. GUID primary key generated using a special algorithm to generate unique primary keys, support for SQL Server and MySQL

Hibernate source in the role of several packages brief introduction

net.sf.hibernate. *

The class of the package are basically interface class and exception classes

net.sf.hibernate.cache. *

JCS implementation class

net.sf.hibernate.cfg. *

Configuration file reading class

net.sf.hibernate.collection. *

The the Hibernate collection interface implementation class, such as List, Set, Bag and so on, Hibernate reason to write your own collection interface implementation class to support lazy loading

net.sf.hibernate.connection. *

Provider of several

net.sf.hibernate.dialect. *

Support a variety of database features, each Dialect achieve class represents a database, the database data types supported and other features, such as whether there AUTOINCREMENT whether there Sequence, paging SQL

net.sf.hibernate.eg. *

The Hibernate documentation used in the example

net.sf.hibernate.engine. *

This package class role is more casual

net.sf.hibernate.expression. *

HQL supports the expression

net.sf.hibernate.hq. *

HQL implementation

net.sf.hibernate.id. *

ID generator

net.sf.hibernate.impl. *

The core of the package, some important interface implementation class, if the Session, SessionFactory, Query, etc.


JCA support, packaging Session interface implementation class support JCA

net.sf.hibernate.jmx. *

I do not know JMX JMX is used to write the App Server hypervisor, is probably the JMX part of the implementation of the interface, making the App Server can be managed via the JMX interface Hibernate

net.sf.hibernate.loader. *

Is also the core of the package, mainly generated SQL statement

net.sf.hibernate.lob. *

BLOB and CLOB support

net.sf.hibernate.mapping. *

the hbm file attributes achieve


Meta implementation of PO

net.sf.hibernate.odmg. *

ODMG an ORM standard, this package is the the ODMG standard implementation class

net.sf.hibernate.persister. *

Core package to achieve lasting mapping between objects and tables

net.sf.hibernate.proxy. *

Proxy and Lazy Loading support

net.sf.hibernate.ps. *

The package is PreparedStatment Cache

net.sf.hibernate.sql. *

Generate the the JDBC sql statement the package

net.sf.hibernate.test. *

Test class, you can use JUnit to test Hibernate


HBM configuration file generated DDL

net.sf.hibernate.transaction. *

The Hibernate Transaction achieve class

net.sf.hibernate.type. *

Hibernate persistent objects defined data types of properties

net.sf.hibernate.util. *

Some tools, the role of scattered

net.sf.hibernate.xml. *

XML data binding

Cache Manager

Hibernate provides two Cache, first-level cache is a cache of the Session level, it is a transaction-scoped cache. This level cache hibernate management, under normal circumstances without the need for intervention; second level cache SessionFactory-level cache, it belongs to the scope of the process or cluster-wide cache. This level of cache can be configured and change, and can be dynamically loaded and unloaded. Hibernate query results of a query cache, it relies on the second-level cache.

1 cache and secondary cache comparison:

The range of the first-level cache second level cache to store data in the form of interrelated bulk data cache of persistent objects object scope of the transaction, each transaction has a separate range of first-level cache process or cluster scope cache is the same process all transactions within or cluster-wide shared concurrent access strategy, as each transaction has a separate first-level cache, does not appear concurrency issues, without having to provide concurrent access strategy the same data multiple transactions simultaneously accessing the second-level cache, must provide appropriate concurrent access strategy, to ensure that the specific transaction isolation level data expiration policies did not provide data expiration policies. Object in a cache never expires, unless the application explicitly clear the cache or clear specific object must provide data expiration policies, such as the maximum number of objects in the cache memory, allowing the object is in the cache the longest time, and allows the objects in the cache the longest idle time physical storage media memory memory and hard disk. The bulk of the object data is first stored in the memory-based cache to the specified limit, when the number of objects in memory of the data expires policy, will the rest of the object is written to the hard disk-based cache. Software implementation of cache cache implementations provided by third parties are included in the implementation of the Hibernate Session to the Hibernate only provide a cache adapter (the cacheProvider). Specific caching plugin integrated into Hibernate. Cache enabled application through the Session interface to execute the save, update, delete, load the operating data and query the database, Hibernate will enable first-level cache copy of the data in the database in the form of objects into the cache, bulk update and bulk delete operations, if you do not want the first-level cache is enabled, you can bypass the Hibernate API directly through JDBC API to perform the operation. Users can configure the second-level cache on the granularity of a single class or a single collection. If the instance of the class is often read but rarely modified, you can consider the use of the second-level cache. Only for a class or collection of the second-level cache is configured, Hibernate will only run an instance of it to the second-level cache. User Management cache physical media of the first-level cache memory, limited memory capacity, must pass the appropriate search strategy and retrieval methods to limit the load object number. , Evit of () method of the Session can explicitly clear the cache object, but this method is not recommendable. The physical medium of the second-level cache memory and hard drive, so the second-level cache can store large amounts of data, data expiration policies maxElementsInMemory attribute values ??can control the number of objects in memory. The second-level cache management mainly includes two aspects: Select the desired use of the second-level cache of persistent classes, set the appropriate concurrent access strategy: Choose a cache adapter, set the appropriate data expiration policies.

2 level cache management:

When the application calls the session save (), update (), the savaeOrUpdate (), get () or load (), and calls the query interface list (), iterate () or filter () method in the Session cache does not yet exist corresponding object, Hibernate will put the object is added to the first-level cache. When to clear the cache, Hibernate will change according to the state of the object cache to synchronize to update the database. Session for the application provides two cache: evict (Object obj): purged from the cache parameters specified persistent object. clear (): empty the cache persistent objects.

3 second-level cache management:

3.1 Hibernate’s second-level cache strategies general process is as follows:

1) criteria query always issues a select * from table_name where …. (all fields) so that the SQL statement to query the database once to get all the data objects.

2) get all data objects based on the ID into the second-level cache.

3) When Hibernate ID to access the data object when the first check from the Session level cache; finding out, if the configuration of the secondary cache, then the check from the second-level cache; finding out, and then query the database, the results into the ID to the cache.

4) delete, update, increase data, updating the cache at the same time.

Hibernate second-level cache strategy is for ID query caching strategy, there is no role for criteria query. To this end, Hibernate provides the Query Cache Query for the conditions.

3.2 What kind of data is suitable for storing the second-level cache? 1 is rarely modified data is not very important data, allowing occasionally concurrent data will not be concurrent access to data reference data refers to the supply with reference constant data, the limited number of instances, it instance referenced by many instances of other classes, instances rarely or never been modified.

3.3 is not suitable for storing data to the second level cache? 1 frequently modified data financial data, and definitely not concurrent shared data with other applications.

3.4 commonly used the caching plugin Hibernater secondary cache is a plug-in, the following are several commonly used caching plugin:

l EhCache: can be used as a process-wide cache, data storage physical media can be memory or hard disk, and provides support for Hibernate query cache.

l OSCache: as a process-wide cache, data storage physical media can be memory or hard disk, provides a rich cache data expiration policies, and provides support for Hibernate query cache.

l SwarmCache: as a cache cluster-wide, but does not support the Hibernate query cache.

l JBossCache: can be used as a cache cluster-wide to support transactional concurrent access policy, and provides support for Hibernate query cache.

3.5 Configuration of the main steps of the second-level cache:

1) Select the persistent classes need to use the second-level cache, set its name cache concurrent access strategy. This step is most worthy of serious consideration.

2) Select the appropriate cache plug-ins, and then edit the configuration file for the plug-in.

Hibernate lazy loading

Hibernate object-relational mapping object initialization delay and non-delay. Non- will be read together with the object of all other objects when reading an object. This can sometimes lead to hundreds (if not thousands) SELECT statement is executed in the read object. This problem sometimes occurs when using the two-way relationship, often resulting in the entire database initialization phase is read out. Of course, you can take the trouble to check the relationship of each object with other objects, and the most expensive deleted, but in the end, we may lose wanted to get ORM tool of convenience.

An obvious solution is to use Hibernate’s lazy loading mechanism. Initialization strategy that targets only one call it one-to-many or many-to-many relationship when the relationship between object read. This process is transparent to developers, and only a few requests for database operations, and would therefore be more significant performance gains. A defect of this technology is to delay the loading technique requires a Hibernate Session object has been open. This will become a major problem in the abstract persistence layer out by using the DAO pattern. The persistence mechanism completely abstract, logical database, including open or close the session, not at the application layer. The most common is the simple interface DAO implementation class database logic package up. A fast but clumsy solution is to abandon the DAO mode, the database connection logic to the application layer. This may be effective for some small applications, but in large systems, this is a serious design flaw that prevents the scalability of the system.

In the Web tier lazy loading

Fortunately, the Spring framework Hibernate lazy loading with DAO integration provides a convenient solution. A Web application, for example, the the Spring provide OpenSessionInViewFilter and OpenSessionInViewInterceptor. We can choose a class to achieve the same functionality. The only difference of the two methods is that the interceptor in the Spring container is running and configured in the web application’s context, filter before the Spring running and configured in web.xml. No matter what, they are open Hibernate session request the current session with the current thread-bound (database). Once bound to the thread, this open Hibernate session in DAO implementation class to use transparent. This session will delay loading values ??in the database object view remains open. Once the logical view, Hibernate session will be closed in the doFilter method of the Filter, or Interceptor postHandle method.

Achieve added in web.xml


<filter-name> hibernateFilter </ filter-name>



</ Filter-class>

</ Filter


<filter-name> hibernateFilter </ filter-name>

<url-pattern> *. do </ url-pattern>

</ Filter-mapping>

Session interface:

Posted by databasesql