hibernate

Introduction to Hibernate Framework

In this article, we will make an introduction to Hibernate Framework.

Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.

Hibernate used its mapping files and configuration files to achieve its objectives. With the introduction of annotations in the java community with JDK 1.5, the Hibernate community started working on Hibernate 3, which had support for annotations. The current version of Hibernate is Hibernate 5.

In this Hibernate example with annotations, we will learn more information on Hibernate, and we will build step by step our first running example application for beginners.

You can also check our Hibernate tutorials for further knowledge.

1. What is Hibernate Framework

Hibernate is an open-source object-relational mapping tool for Java. It provides a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types) but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Mapping Java classes to database tables are accomplished through the configuration of an XML file or by using Java annotations. There are facilities to arrange one-to-many and many-to-many relationships between classes are provided.

In addition to managing associations between objects, Hibernate can also manage reflexive associations where an object has a one-to-many relationship with other instances of its own type.

2. How Hibernate works

Hibernate doesn’t get in our way; nor does it force us to change the way our objects behave. The objects don’t need to implement any magical interfaces in order to be blessed with the ability to persist. All we have to do to put some metadata in the form of annotations telling Hibernate how to use them when mapping them with the database. At runtime, Hibernate reads these annotations and use this information to build queries to send to some relational database.

There is a simple, intuitive API in Hibernate to perform queries against the objects represented by the database, to change those objects we just interact with them normally in the program, and then tell Hibernate to save the changes. Creating new objects is similarly simple; we just create them in the normal way and tell Hibernate about them using annotations so they can get stored in the database.

3. Relation of Hibernate with JPA

JPA (Java Persistence API) is a specification for persistence providers to implement. Hibernate is one such implementation of JPA specification. We can annotate our classes as much as we would like with JPA annotations, however without an implementation, nothing will happen.

When we use Hibernate with JPA we are actually using the Hibernate JPA implementation. The benefit of this is that we can swap out Hibernates implementation of JPA for another implementation of the JPA specification.

When we use straight Hibernate your locking into the implementation because other ORMs may use different methods/configurations and annotations, therefore we cannot just switch over to another ORM.

4. Java Hibernate hello world example

Let’s create our step by step Hibernate hello world example. In this example, I have created an Employee class and declared four attributes id, email, first name, and last name.

I want the id attribute should be generated automatically so that the application code does not store a local cache of employee ids.

So far we targeted what we want to make in our first application. Let’s identify the files that need to be created.

  1. Hibernate.cfg.xml -This configuration file will be used to store database connection information and schema level settings.
  2. EmployeeEntity.java – This class will refer to Java POJOs having Hibernate annotations.
  3. HibernateUtil.java – This class will have utility methods that will be used for creating session factory and session objects.
  4. TestHibernate.java – This class will be used to test our configuration settings and Employee entity annotations.

Before moving into code, let’s see the project setup and adding maven dependencies which need to add to pom.xml to include all compile-time and runtime dependencies.

4.1 Hibernate Maven Dependencies

Our final pom.xml file looks like below.

pom.xml

<dependency>
    <groupid>org.hibernate</groupid>
    <artifactid>hibernate-commons-annotations</artifactid>
    <version>3.0.0.ga</version>
</dependency>
<dependency>
    <groupid>org.hibernate</groupid>
    <artifactid>hibernate-annotations</artifactid>
    <version>3.3.0.ga</version>
</dependency>
<dependency>
    <groupid>mysql</groupid>
    <artifactid>mysql-connector-java</artifactid>
    <version>5.1.6</version>
</dependency>
<dependency>
    <groupid>antlr</groupid>
    <artifactid>antlr</artifactid>
    <version>2.7.6</version>
</dependency>
<dependency>
    <groupid>commons-collections</groupid>
    <artifactid>commons-collections</artifactid>
    <version>3.1</version>
</dependency>
<dependency>
    <groupid>dom4j</groupid>
    <artifactid>dom4j</artifactid>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupid>javassist</groupid>
    <artifactid>javassist</artifactid>
    <version>3.4.GA</version>
</dependency>
<dependency>
    <groupid>javax.transaction</groupid>
    <artifactid>jta</artifactid>
    <version>1.1</version>
</dependency>
<dependency>
    <groupid>org.slf4j</groupid>
    <artifactid>slf4j-api</artifactid>
    <version>1.5.6</version>
</dependency>
<dependency>
    <groupid>org.slf4j</groupid>
    <artifactid>slf4j-log4j12</artifactid>
    <version>1.5.6</version>
</dependency>

Please note that we are not using all maven dependencies in this Hibernate example but they will be used when we start expanding our application.

4.2 Hibernate Configuration

The configuration file contains information about the database and mapping file. Conventionally, its name should be hibernate.cfg.xml .

hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetest</property>
        <property name="hibernate.connection.password">lg225295</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="hibernate.test.dto.EmployeeEntity"></mapping>
    </session-factory>
</hibernate-configuration>

Do not forget to set the correct password before running this Hibernate example.

4.3 Hibernate entity class

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

EmployeeEntity.java

package hibernate.test.dto;
 
import java.io.Serializable;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
 
import org.hibernate.annotations.OptimisticLockType;
 
@Entity
@org.hibernate.annotations.Entity(optimisticLock = OptimisticLockType.ALL)
@Table(name = "Employee", uniqueConstraints = {
        @UniqueConstraint(columnNames = "ID"),
        @UniqueConstraint(columnNames = "EMAIL") })
public class EmployeeEntity implements Serializable {
 
    private static final long serialVersionUID = -1798070786993154676L;
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", unique = true, nullable = false)
    private Integer employeeId;
 
    @Column(name = "EMAIL", unique = true, nullable = false, length = 100)
    private String email;
 
    @Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
    private String firstName;
 
    @Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
    private String lastName;
 
    // Accessors and mutators for all four fields
}

4.4 Hibernate session factory

I have created a utility class HibernateUtil.java where I am creating SessionFactory from XML based configuration.

HibernateUtil.java

package hibernate.test;
 
import java.io.File;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class HibernateUtil 
{
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() 
    {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new AnnotationConfiguration().configure(
                    new File("hibernate.cgf.xml")).buildSessionFactory();
 
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}

Please do not forget to use the correct path of hibernate.cgf.xml.

4.5 Demo

Finally, we will create our demo class TestHibernate.java with the main() method to run the application. We will use this application to save a few Employees’ records.

TestHibernate.java

package hibernate.test;
 
import hibernate.test.dto.EmployeeEntity;
import org.hibernate.Session;
 
public class TestHibernate {
 
    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
 
        // Add new Employee object
        EmployeeEntity emp = new EmployeeEntity();
        emp.setEmail("demo-user@mail.com");
        emp.setFirstName("demo");
        emp.setLastName("user");
 
        session.save(emp);
 
        session.getTransaction().commit();
        HibernateUtil.shutdown();
    }
}

Above code will create a new table employee in the database and insert one row in this table. In logs, you can verify the insert statement which got executed.

Hibernate: insert into Employee (EMAIL, FIRST_NAME, LAST_NAME) values (?, ?, ?)

5. Download the source code

That was an introduction to Hibernate Framework.

Download
You can download the full source code of this example here: Introduction to Hibernate Framework

Simranjit Singh

Simranjit Singh has graduated from Computer Science Department of the Guru Nanak Dev University of Amritsar, Punjab, India. He also holds a Master degree in Software Engineering from the Birla Institute of Technology & Science of Pilani, Rajasthan, India. He works as a Senior Consultant in the e-commerce sector where he is mainly involved with projects based on Java and Big Data technologies.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button