Hibernate tutorial for Beginners

Hibernate is one of the most widely used Java ORM tools. 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 boilerplate 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 a Java-based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa. And there are many benefits of using Hibernate as an ORM tool.

Benefits:

  • 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.
  • Hibernate eliminates all the boilerplate 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.
  • Hibernate supports transaction management and ensures there is no inconsistent data present in the system.
  • Since we use XML, property files, or annotations for mapping Java classes to database tables, it provides an abstraction layer between application and database.
  • Hibernate helps us in mapping joins, collections, inheritance objects and we can easily visualize how our model classes are representing database tables.
  • 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.
  • Hibernate also offers integration with some external modules. For example, Hibernate Validator is the reference implementation of Bean Validation (JSR 303).
  • Hibernate is an open-source project from the Red Hat Community and used worldwide. This makes it a better choice than others because the learning curve is small and there are tons of online documentation and help is easily available in forums.
  • 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 a sample project where we will look into different ways to configure Hibernate in standalone Java applications 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.

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 an 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 contain 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 class 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. An 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 the 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 an 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 an annotations example.

Hibernate Example

When developing Hibernate applications, we need to provide two sets of configuration. The first set of configuration contains database-specific properties that will be used to create a database connection and session objects. The 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 and we can use XML-based or annotation-based configurations for providing model classes and database table mapping. We will use JPA annotations from javax.persistence for annotation-based mappings.

Our final project will look like the below image:

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 a MySQL database and the below script is used to create the necessary table:

CREATE TABLE `Employee` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  `role` varchar(20) DEFAULT NULL,
  `insert_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;

Notice that the Employee table’s 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:

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.journaldev.hibernate</groupId>
  <artifactId>HibernateExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>HibernateExample</name>
  
  <dependencies>
  	<dependency>
  		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate-core</artifactId>
  		<version>4.3.5.Final</version>
  	</dependency>
  	<!-- Hibernate 4 uses Jboss logging, but older versions slf4j for logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
        	<groupId>mysql</groupId>
        	<artifactId>mysql-connector-java</artifactId>
        	<version>5.0.5</version>
        </dependency>
  </dependencies>
  
  <build>
  	<finalName>${project.artifactId}</finalName>
  </build>
</project>

The 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 the latest Hibernate version (4.3.5.Final) for my sample project. Hibernate is still evolving, and I have observed that a lot of core classes change between major releases. So if you are using another version, you might need to modify the Hibernate configurations slightly for it to work. However, it should work fine for all the 4.x.x releases. Hibernate 4 uses JBoss logging, but older versions use slf4j for logging purposes, so I have included the slf4j-simple artifact in my project, although not needed because I am using Hibernate 4. The mysql-connector-java artifact is the MySQL driver for connecting to MySQL databases. If you are using any other database, add the corresponding driver artifact.

Domain Model Classes

As you can see in the below code, we have two model classes: Employee and Employee1. Employee is a simple Java Bean class, and we will use XML-based configuration for providing its mapping details. Employee1 is a Java Bean where fields are annotated with JPA annotations, so we don’t need to provide mapping in a separate XML file.

package com.journaldev.hibernate.model;

import java.util.Date;

public class Employee {

  private int id;
  private String name;
  private String role;
  private Date insertTime;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getRole() {
    return role;
  }
  public void setRole(String role) {
    this.role = role;
  }
  public Date getInsertTime() {
    return insertTime;
  }
  public void setInsertTime(Date insertTime) {
    this.insertTime = insertTime;
  }
}

The Employee class is a simple Java Bean, and there is nothing specific to discuss here.

package com.journaldev.hibernate.model;

import java.util.Date;

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;

@Entity
@Table(name="Employee", 
       uniqueConstraints={@UniqueConstraint(columnNames={"ID"})})
public class Employee1 {

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  @Column(name="ID", nullable=false, unique=true, length=11)
  private int id;
  
  @Column(name="NAME", length=20, nullable=true)
  private String name;
  
  @Column(name="ROLE", length=20, nullable=true)
  private String role;
  
  @Column(name="insert_time", nullable=true)
  private Date insertTime;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getRole() {
    return role;
  }
  public void setRole(String role) {
    this.role = role;
  }
  public Date getInsertTime() {
    return insertTime;
  }
  public void setInsertTime(Date insertTime) {
    this.insertTime = insertTime;
  }
}

The @Entity annotation is used to mark a class as an entity bean that can be persisted by Hibernate. Since Hibernate provides JPA implementation, we use @Entity. The @Table annotation is used to define the table mapping and unique constraints for the columns. The @Id annotation defines the primary key for the table. The @GeneratedValue annotation specifies that the field will be auto-generated, and GenerationType.IDENTITY is used to map the generated ID value to the bean and retrieve it in the Java program. The @Column annotation maps the field with the table column and allows specifying length, nullable, and uniqueness for the bean properties.

Hibernate Mapping XML Configuration

As stated above, we will use XML-based configuration for the Employee class mapping. We can choose any name for the mapping file, but it’s good practice to use the table or Java bean name for clarity. Our Hibernate mapping file for the Employee bean looks like the following:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
	<class name="com.journaldev.hibernate.model.Employee" table="EMPLOYEE">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="increment" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="role" type="java.lang.String">
            <column name="ROLE" />
        </property>
        <property name="insertTime" type="timestamp">
        	<column name="insert_time" />
        </property>
    </class>
</hibernate-mapping>

The XML configuration is simple and does the same thing as the 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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Database connection properties - Driver, URL, user, password -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
		<property name="hibernate.connection.username">pankaj</property>
		<property name="hibernate.connection.password">pankaj123</property>
		<!-- Connection Pool Size -->
		<property name="hibernate.connection.pool_size">1</property>
		
		<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
		<property name="hibernate.current_session_context_class">thread</property>
		
		<!-- Outputs the SQL queries, should be disabled in Production -->
		<property name="hibernate.show_sql">true</property>
		
		<!-- Dialect is required to let Hibernate know the Database Type, MySQL, Oracle etc
			Hibernate 4 automatically figure out Dialect from Database Connection Metadata -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 

		<!-- mapping file, we can use Bean annotations too --> 
		<mapping resource="employee.hbm.xml" />
	</session-factory>
</hibernate-configuration>

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"https://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Database connection properties - Driver, URL, user, password -->
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost/TestDB</property>
		<property name="hibernate.connection.username">pankaj</property>
		<property name="hibernate.connection.password">pankaj123</property>
		
		<!-- org.hibernate.HibernateException: No CurrentSessionContext configured! -->
		<property name="hibernate.current_session_context_class">thread</property>
		
		<!-- Mapping with model class containing annotations -->
		<mapping class="com.journaldev.hibernate.model.Employee1"/>
	</session-factory>
</hibernate-configuration>

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.

package com.journaldev.hibernate.util;

import java.util.Properties;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.journaldev.hibernate.model.Employee1;

public class HibernateUtil {

  // XML-based configuration
  private static SessionFactory sessionFactory;

  // Annotation-based configuration
  private static SessionFactory sessionAnnotationFactory;

  // Java-based configuration
  private static SessionFactory sessionJavaConfigFactory;

  private static SessionFactory buildSessionFactory() {
    try {
      Configuration configuration = new Configuration();
      configuration.configure("hibernate.cfg.xml");
      System.out.println("Hibernate Configuration loaded");

      ServiceRegistry serviceRegistry = 
          new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
      System.out.println("Hibernate serviceRegistry created");

      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

      return sessionFactory;
    } catch (Throwable ex) {
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

  private static SessionFactory buildSessionAnnotationFactory() {
    try {
      Configuration configuration = new Configuration();
      configuration.configure("hibernate-annotation.cfg.xml");
      System.out.println("Hibernate Annotation Configuration loaded");

      ServiceRegistry serviceRegistry = 
          new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
      System.out.println("Hibernate Annotation serviceRegistry created");

      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

      return sessionFactory;
    } catch (Throwable ex) {
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

  private static SessionFactory buildSessionJavaConfigFactory() {
    try {
      Configuration configuration = new Configuration();

      // Create properties, can be read from a properties file
      Properties props = new Properties();
      props.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
      props.put("hibernate.connection.url", "jdbc:mysql://localhost/TestDB");
      props.put("hibernate.connection.username", "username");
      props.put("hibernate.connection.password", "password");
      props.put("hibernate.current_session_context_class", "thread");

      configuration.setProperties(props);

      // Annotated class
      configuration.addAnnotatedClass(Employee1.class);

      ServiceRegistry serviceRegistry = 
          new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
      System.out.println("Hibernate Java Config serviceRegistry created");

      SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

      return sessionFactory;
    } catch (Throwable ex) {
      System.err.println("Initial SessionFactory creation failed." + ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) sessionFactory = buildSessionFactory();
    return sessionFactory;
  }

  public static SessionFactory getSessionAnnotationFactory() {
    if (sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
    return sessionAnnotationFactory;
  }

  public static SessionFactory getSessionJavaConfigFactory() {
    if (sessionJavaConfigFactory == null) sessionJavaConfigFactory = buildSessionJavaConfigFactory();
    return sessionJavaConfigFactory;
  }
}

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:

Creating Configuration object and configure it
Creating ServiceRegistry object and apply configuration settings.
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

Here is a test program that uses the XML-based configuration:

package com.journaldev.hibernate.main;

import java.util.Date;

import org.hibernate.Session;

import com.journaldev.hibernate.model.Employee;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateMain {

  public static void main(String[] args) {
    Employee emp = new Employee();
    emp.setName("John");
    emp.setRole("Manager");
    emp.setInsertTime(new Date());

    // Get Session
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    // Start transaction
    session.beginTransaction();
    // Save the Model object
    session.save(emp);
    // Commit transaction
    session.getTransaction().commit();
    System.out.println("Employee ID=" + emp.getId());

    // Terminate session factory, otherwise program won't end
    HibernateUtil.getSessionFactory().close();
  }
}

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


 
May 06, 2014 12:40:06 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 06, 2014 12:40:06 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 06, 2014 12:40:06 AM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
May 06, 2014 12:40:06 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
May 06, 2014 12:40:06 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
May 06, 2014 12:40:07 AM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: employee.hbm.xml
May 06, 2014 12:40:08 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Configuration loaded
Hibernate serviceRegistry created
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
May 06, 2014 12:40:08 AM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 06, 2014 12:40:08 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 06, 2014 12:40:08 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select max(ID) from EMPLOYEE
Hibernate: insert into EMPLOYEE (NAME, ROLE, insert_time, ID) values (?, ?, ?, ?)
Employee ID=19
May 06, 2014 12:40:08 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]


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

Hibernate Annotation Configuration Test

Here is a test program that uses the annotation-based configuration:

package com.journaldev.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.journaldev.hibernate.model.Employee1;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateAnnotationMain {

  public static void main(String[] args) {
    Employee1 emp = new Employee1();
    emp.setName("Alice");
    emp.setRole("Developer");
    emp.setInsertTime(new Date());

    // Get Session
    SessionFactory sessionFactory = HibernateUtil.getSessionAnnotationFactory();
    Session session = sessionFactory.getCurrentSession();
    // Start transaction
    session.beginTransaction();
    // Save the Model object
    session.save(emp);
    // Commit transaction
    session.getTransaction().commit();
    System.out.println("Employee ID=" + emp.getId());

    // Terminate session factory, otherwise program won't end
    sessionFactory.close();
  }
}

When we execute above program, we get following output.

 

May 06, 2014 12:42:22 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 06, 2014 12:42:22 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 06, 2014 12:42:22 AM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
May 06, 2014 12:42:22 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
May 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate-annotation.cfg.xml
May 06, 2014 12:42:22 AM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate-annotation.cfg.xml
May 06, 2014 12:42:23 AM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Hibernate Annotation Configuration loaded
Hibernate Annotation serviceRegistry created
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 06, 2014 12:42:23 AM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 06, 2014 12:42:23 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 06, 2014 12:42:23 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee ID=20
May 06, 2014 12:42:23 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

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

Here is a test program that uses the Java-based configuration:

package com.journaldev.hibernate.main;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.journaldev.hibernate.model.Employee1;
import com.journaldev.hibernate.util.HibernateUtil;

public class HibernateJavaConfigMain {

  public static void main(String[] args) {
    Employee1 emp = new Employee1();
    emp.setName("Bob");
    emp.setRole("HR");
    emp.setInsertTime(new Date());

    // Get Session
    SessionFactory sessionFactory = HibernateUtil.getSessionJavaConfigFactory();
    Session session = sessionFactory.getCurrentSession();
    // Start transaction
    session.beginTransaction();
    // Save the Model object
    session.save(emp);
    // Commit transaction
    session.getTransaction().commit();
    System.out.println("Employee ID=" + emp.getId());

    // Terminate session factory, otherwise program won't end
    sessionFactory.close();
  }
}

Output of the above test program is:

 
May 06, 2014 12:45:09 AM org.hibernate.annotations.common.reflection.java.JavaReflectionManager 
INFO: HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
May 06, 2014 12:45:09 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.5.Final}
May 06, 2014 12:45:09 AM org.hibernate.cfg.Environment 
INFO: HHH000206: hibernate.properties not found
May 06, 2014 12:45:09 AM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Hibernate Java Config serviceRegistry created
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH000402: Using Hibernate built-in connection pool (not for production use!)
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/TestDB]
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=pankaj, password=****}
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
May 06, 2014 12:45:09 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
May 06, 2014 12:45:10 AM org.hibernate.dialect.Dialect 
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
May 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
May 06, 2014 12:45:10 AM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
May 06, 2014 12:45:10 AM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Employee ID=21
May 06, 2014 12:45:10 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH000030: Cleaning up connection pool [jdbc:mysql://localhost/TestDB]

Conclusion

That’s all for this Hibernate tutorial for beginners. We have covered:

  • Understanding Hibernate and its benefits
  • Configuring Hibernate using XML, annotations, and Java-based configurations
  • Writing test programs to insert records into the database

I hope this tutorial provides you with a solid foundation for working with Hibernate in your Java applications. You can now explore more advanced topics like query optimizations, caching, and integration with frameworks like Spring.

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in:

centron Managed Cloud Hosting in Deutschland

How to Calculate BLEU Score in Python?

Python
How to Calculate BLEU Score in Python? BLEU score in Python is a metric that measures the goodness of Machine Translation models. Though originally it was designed for only translation…