Hibernate Tutorial For Beginners With Examples

Welcome to the Hibernate tutorial for Beginners. Hibernate is one of the most widely used Java ORM tool. Most of the applications use relational databases to store application information and at the low level we use JDBC API for connecting to databases and perform CRUD operations.

Hibernate Tutorial for Beginners

If you look at the JDBC code, there is so much of boiler plate code and there are chances of resource leak and data inconsistency because all the work needs to be done by the developer. This is where an ORM tool comes handy.

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa.

Some of the benefits of using Hibernate as ORM tool are:

  1. Hibernate supports mapping of java classes to database tables and vice versa. It provides features to perform CRUD operations across all the major relational databases.
  2. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business use cases rather than making sure that database operations are not causing resource leaks.
  3. Hibernate supports transaction management and make sure there is no inconsistent data present in the system.
  4. Since we use XML, property files or annotations for mapping java classes to database tables, it provides an abstraction layer between application and database.
  5. Hibernate helps us in mapping joins, collections, inheritance objects and we can easily visualize how our model classes are representing database tables.
  6. Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
  7. Hibernate also offers integration with some external modules. For example Hibernate Validator is the reference implementation of Bean Validation (JSR 303).
  8. Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
  9. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.

I hope all the above benefits will convince you that Hibernate is the best choice for your application object-relational mapping requirements. Let’s look at the Hibernate Framework architecture now and then we will jump into sample project where we will look into different ways to configure Hibernate in standalone java application and use it.

Hibernate Architecture

Below image shows the Hibernate architecture and how it works as an abstraction layer between application classes and JDBC/JTA APIs for database operations. It’s clear that Hibernate is built on top of JDBC and JTA APIs.

Hibernate-Architecture-Diagram

Let’s look at the core components of hibernate architecture one by one.

  • SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We can get instance of org.hibernate.Session using SessionFactory.
  • Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction.
  • Persistent objects: Persistent objects are short-lived, single threaded objects that contains persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session.
  • Transient objects: Transient objects are persistent classes instances that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.
  • Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
  • ConnectionProvider (org.hibernate.connection.ConnectionProvider): ConnectionProvider is a factory for JDBC connections. It provides abstraction between the application and underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended by the developer.
  • TransactionFactory (org.hibernate.TransactionFactory): A factory for org.hibernate.Transaction instances.

Hibernate and Java Persistence API (JPA)

Hibernate provides implementation of Java Persistence API, so we can use JPA annotations with model beans and hibernate will take care of configuring it to be used in CRUD operations. We will look into this with annotations example.

Hibernate Example

When developing hibernate applications, we need to provide two set of configuration. First set of configuration contains database specific properties that will be used to create Database connection and Session objects. Second set of configurations contains mapping between model classes and database tables.

We can use XML based or properties based configuration for database connection related configurations. We can use XML based or annotation based configurations for providing model classes and database tables mapping. We will use JPA annotations from javax.persistence for annotation based mappings.

Our final project will look like below image.

Hibernate-Architecture-Diagram

Create a Maven project in Eclipse or your favorite IDE, you can keep any name of your choice. Before we move on to the different components of the project, we will have to do the database setup.

Database Table Setup

For my example, I am using MySQL database and below script is used to create necessary table.

Notice that Employee table “id” column is automatically generated by MySQL, so we don’t need to insert it.

Hibernate Project Dependencies

Our final pom.xml file looks like below.

hibernate-core artifact contains all the core hibernate classes, so we will get all the necessary features by including it in the project.

Note that I am using latest Hibernate version (4.3.5.Final) for my sample project and Hibernate is still evolving and I have seen that a lot of core classes change between every major release. So if you are using any other version, there is a small chance that you will have to modify the Hibernate configurations for it to work. However, I am sure that it will work fine for all the 4.x.x releases.

Hibernate 4 uses JBoss logging but older versions uses slf4j for logging purposes, so I have included slf4j-simple artifact in my project, although not needed because I am using Hibernate 4.

mysql-connector-java is the MySQL driver for connecting to MySQL databases, if you are using any other database then add corresponding driver artifact.

Domain Model Classes

As you can see in above image that we have two model classes, Employee and Employee1.

Employee is a simple Java Bean class and we will use XML based configuration for providing it’s mapping details.

Employee1 is a java bean where fields are annotated with JPA annotations, so that we don’t need to provide mapping in separate XML file.

Employee class is simple java bean, there is nothing specific to discuss here.

javax.persistence.Entity annotation is used to mark a class as Entity bean that can be persisted by hibernate, since hibernate provides JPA implementation.

javax.persistence.Table annotation is used to define the table mapping and unique constraints for the columns.

javax.persistence.Id annotation is used to define the primary key for the table. javax.persistence.GeneratedValue is used to define that the field will be auto generated and GenerationType.IDENTITY strategy is used so that the generated “id” value is mapped to the bean and can be retrieved in the java program.

javax.persistence.Column is used to map the field with table column, we can also specify length, nullable and uniqueness for the bean properties.

Hibernate Mapping XML Configuration

As stated above, we will use XML based configuration for Employee class mapping. We can choose any name, but it’s good to choose with table or java bean name for clarity. Our hibernate mapping file for Employee bean looks like below.

employee.hbm.xml

The xml configuration is simple and does the same thing as annotation based configuration.

Hibernate Configuration Files

We will create two hibernate configuration xml files – one for xml based configuration and another for annotation based configuration.

hibernate.cfg.xml

Most of the properties are related to database configurations, other properties details are given in comment. Note the configuration for hibernate mapping file, we can define multiple hibernate mapping files and configure them here. Also note that mapping is specific to session factory.

hibernate-annotation.cfg.xml

Most of the configuration is same as XML based configuration, the only difference is the mapping configuration. We can provide mapping configuration for classes as well as packages.

Hibernate SessionFactory

I have created a utility class where I am creating SessionFactory from XML based configuration as well as property based configuration. For property based configuration, we could have a property file and read it in the class, but for simplicity I am creating Properties instance in the class itself.

Creating SessionFactory for XML based configuration is same whether mapping is XML based or annotation based. For properties based, we need to set the properties in Configuration object and add annotation classes before creating the SessionFactory.

Overall creating SessionFactory includes following steps:

  1. Creating Configuration object and configure it
  2. Creating ServiceRegistry object and apply configuration settings.
  3. Use configuration.buildSessionFactory() by passing ServiceRegistry object as argument to get the SessionFactory object.

Our application is almost ready now, let’s write some test programs and execute them.

Hibernate XML Configuration Test

Our test program looks like below.

The program is self understood, when we execute the test program, we get following output.

Notice that it’s printing the generated employee id, you can check database table to confirm it.

Hibernate Annotation Configuration Test

When we execute above program, we get following output.

Have a look at the output and compare it with the output from the XML based configuration, you will notice some differences. For example, we are not setting connection pool size for annotation based configuration, so it’s setting to default value 20.

Hibernate Java Configuration Test

Output of the above test program is:

That’s all for hibernate tutorial for beginners, I hope it will be enough to get you started. We will look into different features of Hibernate framework in future tutorials. Download the complete project from below link and play around with it to learn more.

By admin

Leave a Reply