× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Hibernate 4: Whats new?

This articles deals with some of the new features in Hibernate 4, the most popular Java object/relational mapping framework today. Among the novelties brought by versions 4.0, 4.1 and 4.2 the current CR (Candidate Release).

Hibernate is the object/relational mapping framework best known and used for the Java platform today. It was also one of the pioneers of this kind of persistence solution and was used as a basis for the definition of the Java Persistence API 2.0 standard, given its popularity.

In his many years of existence, the project grew and launched several subprojects such as Hibernate Shards (for persistence in distributed databases), Hibernate Search (bringing more advanced features of textual research to the database), Hibernate Validator (implementation reference JSR 303 - Bean Validation), Hibernate OGM (for NoSQL solutions), among others. We will discuss the core framework, which at the time of creation of the subprojects was called Hibernate Core, but is now known as Hibernate ORM. We will use all these names (Hibernate, Hibernate Core and Hibernate ORM) to refer to the same framework.

In December 2011, JBoss (the company that coordinates the development of the framework) has released version 4.0 of Hibernate ORM, registering a jump from the previous version, 3.6.9. In February 2012 there was a smaller breakthrough with the release of version 4.1. In late January, was published Candidate Release (CR) of the 4.2 version of the framework core. While many users eager for new features were already using Hibernate 4.x for months, probably the most conservative clung to some family version 3.x until the new versions were more stable.

In all these developments, from 4.0 more than a year ago to the most recent CR Hibernate ORM 4.2, some new features have been added to the framework over version 3.6. According to the developers themselves, on his blog (see Links), we highlight the following:

  • A new way to obtain the SessionFactory, after unification of existing services in the framework of a single record;
  • Adequacy framework to OSGi platform (see Links), dividing the classes in each of their packages into three categories: public, internal and SPI (Service Provider Interface);
  • Support to multi-tenant databases. Databases such those store data from different organizations (tenants) in the same instance, managing access to each of its data;
  • A new API for retrieving objects using natural identifiers. These identifiers are those that are part of the problem domain and were not added artificially only by persistence issues;
  • Verification of dirty objects (dirty checking) customizable by the customer. In other words, the framework allows the user's own specify when an object should be considered dirty (ie, has been modified in relation to the database) or not;
  • Internationalization of the log messages using JBoss Logging;
  • Use of the JDK 1.6 and JDBC 4 as the basis for development.

In this paper, we present examples using some of the features listed above. We begin, however, with download instructions and "installation" of the framework.

Download and Installation

Hibernate ORM can be obtained on the official site framework (see Links), in the Downloads section. It is distributed in two ways: packets containing binary distribution, and document sources or by means of a repository Maven artifacts.

The Maven is a software project management tool that allows a developer to indicate the dependencies of a project (for example, Hibernate framework) and trust the tool to obtain the required JAR files, including any transitive dependency, repositories on the Internet.

In the first case, the distribution in a package (ZIP or TGZ) when uncompressed provides all the files needed to use the framework in the lib folder. This folder is further subdivided into four folders:

  • Lib/required: JARs that are required to use Hibernate. If you are setting the classpath of your project manually, these are the files to be added for use of the framework;
  • Lib/jpa: JAR present in this directory contains the classes that implement the Hibernate support standard JPA (Java Persistence API), if the developer prefers to use this standard interface instead of the specific framework API;
  • Lib/envers: This folder contains the framework of audit JBoss Envers entities. This framework records the history of changes in certain attributes of persistent entities for future audit;
  • Lib/optional: this folder contains JARs for the optional framework features such as use of the pool C3P0 connections or ehcache cache instead of the solutions used by default if no specific configuration is made (these settings are outside the scope of this article) .

The most practical solution, however, is to use a dependency management tool, such as that offered by Maven. The following are the instructions for creating a project managed by Maven and inclusion of Hibernate 4 as dependency. To follow these instructions, you must have installed the Eclipse IDE and the plug-in m2e - Maven Integration for Eclipse. The first can be obtained free of charge on its website while the latter can be installed within Eclipse itself, opening the Help > Install New Software menu, selecting the repository and filtering packages available for m2e.

Once installed the m2e and restarted Eclipse, create a new project Maven Project type. During the wizard for creating this project, select the option Create a simple project and at the last screen of the wizard, complete project information as shown in Figure 1.

Information for creating a project in Eclipse-based Maven.

Figure 1. Information for creating a project Maven-based in Eclipse.

With the steps to create the completed project, we can add the Hibernate as addiction. However, for the framework directly from the manufacturer, you must add the JBoss Maven repository to settings. To do so, follow the steps below:

  1. Open the preferences of Eclipse (Eclipse > Preferences or Window > Preferences, depending on the operating system) and navigate to the option Maven > User Settings;
  2. User Settings field indicates the file that contains the Maven settings for your user (ex .: /Users/mrbool/.m2/settings.xml). Locate this file on your system and open it with a text editor. If the Eclipse show alert "User settings file does not exist", it means that the file does not yet exist and therefore should be established;
  3. Fill the file with the contents of Listing 1. If you already have a Maven configuration, include the JBoss repositories in your configuration profile;
  4. Return to the Eclipse preferences, section Maven > User Settings and click in the Update Settings button.

Listing 1. Maven configuration to use the artifacts repository of JBoss.

       <name>JBoss Public Maven Repository Group</name>
       <name>JBoss Public Maven Repository Group</name>

With the configured repository, open the pom.xml file of the project previously established for the specific Eclipse editor (provided by the plug-in m2e). Go to the Dependencies tab (located on the bottom of the editor) and, in the Dependencies column (left), click the Add button. In the dialog box that opens, there is a search field above the Search Results field. Look for hibernate-core and select the artifact that is in org.hibernate group, as shown in Figure 2.

Note that the value of the version attribute may vary depending on the final version of the framework at the time you are following these instructions. You can also specify a different version of the framework to use, if desired (ex .: 4.1.10.Final). If the item org.hibernate hibernate-core shown in Figure 2 is expanded, will be presented all framework versions available in the repository and you can choose the one you want.

Adding Hibernate as dependence on the project using Maven in Eclipse.

Figure 2. Adding Hibernate as dependence on the project using Maven in Eclipse.

Repeat the operation to include three other dependencies (group / artifact / version):

  • com.h2database / h2 / 1.3.170 (in-memory database that will be used for example),
  • org.jboss / jandex / 1.0.3. Final
  • and com.fasterxml / classmate / 0.5.4 (tools that Hibernate requires to perform code introspection activities).

Note that the latter is added to the POM as bundle type and you need to change it to jar type by clicking the Properties button. After these additions, the source code of the pom.xml file (available in the latest editor tab) should be similar to Listing 2.

Listing 2. Newly created project Maven configuration, including Hibernate, H2, and Jandex Classmate as dependencies.

<project xmlns="http://maven.apache.org/POM/4.0.0"

After saving the file, Eclipse will, behind the scenes, retrieve all the JAR files needed to use Hibernate in this project. In the Package Explorer view, under the project created, you can see the Maven Dependencies item, containing all the JARs being added to the project classpath. At this point, your project is ready to use Hibernate. If you are not using Maven, check out the Links list the sites where you can download the H2 database and Jandex Classmate and tools.

Example for illustration

With the framework installed and ready for use, we will create a small application for managing an address book, which will be used later to illustrate what's new in Hibernate 4. The system has a text-only interface (terminal style or "command prompt") possible with the following commands:

  • ?: Print this list of commands;
  • usu: change the current user. Use: usu ;
  • list: list the names of the registered contacts and their IDs;
  • add: add a new contact. Use: add ;
  • show: shows details of a specific contact. Use: show ;
  • del: Deletes a specific contact. Use: del ;
  • exit: exit.

This simple system has only a persistent class called Contact, whose source code is shown in Listing 3.

Listing 3. Source code of the Contact class, single persistent entity in the illustrative example.

package com.mrbool.agenda.domain;

import java.util.Date;
import javax.persistence.*;
public class Contact {
   @Id @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String name;
   private String email;
   private String phone;
   private Date lastUpdateDate;
   /* get/set for all attributes. */

As can be seen, the mapping of the Contact class to the relational world is done through annotations, using the annotations defined in javax.persistence package, part of the Java API. The class is defined as a persistent entity using theEntity annotation. @Id and @GeneratedValue identify the attribute of this class to serve as a primary key in the database table, setting automatic generation of values for this column. String attributes are not recorded, but the default is every attribute be persisted unless otherwise stated. Finally, @Temporal(TemporalType.TIMESTAMP) specifies that from the lastUpdateDate attribute should be stored both date and time.

To use this class with Hibernate, you just need to create the hibernate.cfg.xml file with the general configuration of the framework (connection, cache, dialect, etc.) and instantiate a session factory from it. Listing 4 shows an example configuration file that could be used to implement the example. However, as will be seen later in the article, to illustrate the new features of Hibernate 4 programmatic configuration is used.

Listing 4. Example of general configuration of Hibernate, hibernate.cfg.xml file.

<?xml version='1.0' encoding='utf-8'?>
  <hibernate-configuration xmlns="http://www.hibernate.org/xsd/hibernate-configuration">
    <property name="hibernate.connection.driver_class">org.h2.Driver</property>
    <property name="hibernate.connection.url">
    <property name="hibernate.connection.username">your_user_name</property>
    <property name="hibernate.connection.password"></property>
    <property name="hibernate.connection.pool_size">1</property>
    <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
    <property name="hibernate.cache.provider_class">
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <mapping class="com.mrbool.agenda.domain.Contact" />

The commands listed above, that manipulate instances of the Contact class, and the user interface are implemented in com.mrbool.agenda.domain.Contact class. This and other classes are part of the sample application and some of its parts will be displayed throughout the article. It is not necessary, however, to show them here in full.

Service Registry

Hibernate was already a well extensible framework. For example, new databases dialects can be created and used, how Hibernate accesses the attributes of the objects can be changed to a custom shape, interceptors can be run at various points of the persistent cycle, etc.

Now in version 4, in the spirit of the OSGi platform, Hibernate is even more extensible, declaring various types of framework functionality as services, with a well defined interface and therefore likely to be replaced by customized versions, developed by its users. The implementation framework that had every feature is still offered, of course, as the default implementation of the service in question.

Developers who require a specialized behavior towards any of the Hibernate services no longer have to change the source code of the framework, simply create a new implementation of the service in question and plug it to the record. New services can also be created since they extend the org.hibernate.service.Service interface.

The implementation of a service can declare dependence on the interface of another service through the annotation @org.hibernate.service.spi.InjectService and have it injected automatically by the framework. Another option is to locate the service required directly on record that, in turn, can be injected if the service that implements the interface org.hibernate.service.spi.ServiceRegistryAwareService.

Through the service entry, overwrite or extend the framework was easier. The task, however, is not easy and requires advanced knowledge of operating an ORM framework, requiring in very specific cases (by the framework definition, the most common cases have been designed and developed). The change, however, affect 'common' users of the framework in a common task: the creation of the session factory.

Like any Hibernate user already knows, to perform persistence operations using the framework you need to open a session of use (class org.hibernate.Session), consisting of an object that abstracts the connection and communication with the database via JDBC. For instances of this class, you must create a (usually single) session factory (org.hibernate.SessionFactory class).

By the Hibernate 3, the code to create a session factory from the hibernate.cfg.xml configuration file (such as the one shown in Listing 4) was like the code shown in Listing 5. Starting with version 4, is possible to get the session factory associating it with a central registry framework, as shown in Listing 6.

Listing 5. Former way to obtain the Hibernate session factory.

Configuration cfg = new Configuration().configure(); 
SessionFactory sessionFactory = cfg.buildSessionFactory();

Listing 6. New ways of obtaining the session factory Hibernate.

 // Using the Configuration class:
  Configuration cfg = new Configuration().configure();
  ServiceRegistryBuilder registryBuilder = new ServiceRegistryBuilder();
  ServiceRegistry registry = registryBuilder.buildServiceRegistry();
  SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
  // Without using the Configuration class:
  ServiceRegistry registry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
  MetadataSources sources = new MetadataSources(registry);
  Metadata metadata = sources.buildMetadata();
  SessionFactory sessionFactory = metadata.buildSessionFactory();

Listing 6 shows two ways of obtaining the session factory. The first is similar to the method used previously, based on a Configuration object. The difference is that it also created a record of services (ServiceRegistry) from a builder object (ServiceRegistryBuilder). The applySettings() method of the object constructor applies the same settings of the config object to the registry to be created. Finally, the session factory is created by passing the record as a parameter so that Hibernate can access the services through it.

The second form does not use the Configuration class, setting the builder object registration services through a specific method: configure(). The registry service is just created and then passed as a parameter to create an instance of MetadataSources. After adding the persistent classes of that body (note: in the case of XML via mapping should be used addResource() instead of addAnnotatedClass()), it is used to build the meta-data that ultimately are in turn used to construct the session factory.

Although more verbose, new ways to get the session factory using the central registry, allowing overwritten and extension of the framework. For this reason, the old form is marked as deprecated and must be removed in version 5.0 of the framework.

All three ways to get the session factory assume that a hibernate.cfg.xml configuration file is in the root of the classpath (there are ways to specify your location, otherwise). However, the sample application does not use this configuration file.


This paper has presented some of the new features of version 4 of the Hibernate framework (some of which are present since version 4.0, other added in increments 4.1 or 4.2): the new central registry services (and how it affects the creation of sessions factory) the use of multi-tenant database and the definition of persistent identifiers natural classes. Such features were addressed by example that revolved around a simple application for managing contacts called Calendar.

As the Hibernate evolves within the 4.x series news analyzed become more robust and reliable, ready to be adopted by real systems development projects to be implemented and made available to its users. Some obstacles, however, still present: the setting to use multi-tenant database is still quite complex and changes in the API cause confusion with respect to configuration files (exceptions were launched for the file format in some cases).

It is expected, however, that the continued development of this open source framework to resolve the outstanding problems and that he keep as mapping solution object / relational most popular for the Java platform.

Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login