How to configure hibernate in Java application

In the previous article, we have seen How to set up an environment for Hibernate Development you can check it here Environment Set up for Hibernate. In this article, we will cover What is Hibernate Configuration?

As we know, ORM tools help us to map the Java classes into the database table. So, Hibernate needs to know where is the information of the mapping files in an application. So, this information is provided in the Hibernate configuration file.

What is Hibernate Configuration?

Hibernate configuration contains information on the mapping of Java classes into the database table. This information is supply by using any of the two files

  • hibernate.properties
  • hibernate.cfg.xml

Let’s see hibernate.properties file configuration

hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/demo
hibernate.connection.username = root
hibernate.connection.password = root
hibernate.c3p0.min_size=5
hibernate.c3p0.max_size=20
hibernate.c3p0.timeout=1800
hibernate.c3p0.max_statements=50
hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Let’s see hibernet.cgf.xml configuration

<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
   <session-factory>
   
      <property name = "hibernate.dialect">
         org.hibernate.dialect.MySQLDialect
      </property>
      
      <property name = "hibernate.connection.driver_class">
         com.mysql.jdbc.Driver
      </property>
      
      <!-- demo is the database name -->
      
      <property name = "hibernate.connection.url">
         jdbc:mysql://localhost/demo
      </property>
      
      <property name = "hibernate.connection.username">
         root
      </property>
      
      <property name = "hibernate.connection.password">
         root
      </property>
      
      <!-- List of XML mapping files -->
      <mapping resource = "Student.hbm.xml"/>
      
   </session-factory>
</hibernate-configuration>

Let’s understand the configuration file in detail

First, create a database demo using MySQL workbench. create an XML configuration file we must use DTD(Document Type Definition)  for Hibernate (the version we are using).

Syntax

<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

Dialects in Hibernate

The dialect in the hibernate.cg.xml file specifies which type of database we will use in our application. To connect with the database we need to provide the SQL dialect in the configuration file.

Syntax

<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

As we know there are many RDBMS available in the market so we have different dialects available for each of them let’s see some of the database and dialect associate with it.

  • Oracle: org.hibernate.dialect.OracleDialect
  • MySQL: org.hibernate.dialect.MySQLDialect
  • DB2: org.hibernate.dialect.OracleDialect
  • Microsoft SQL Server: org.hibernate.dialect.SQLServerDialect
  • PostgreSQL: org.hibernate.dialect.PostgreSQLDialect
  • SAPDB: org.hibernate.dialect.SAPDBDialect
  • Informix: org.hibernate.dialect.InformixDialect
  • HypersonicSQL: org.hibernate.dialect.HypersonicSQLDialect
  • Ingres:org.hibernate.dialect.Ingres
  • Progress: org.hibernate.dialect.ProgressDialect
  • Oracle9i: org.hibernate.dialect.Oracle9iDialect
  • Oracle10g: org.hibernate.dialect.Oracle10gDialect
  • Oracle11g: org.hibernate.dialect.Oracle11gDialect
  • Interbase:org.hibernate.dialect.Interbase
  • HSQLDB:org.hibernate.dialect.HSQLDB

JDBC properties

We must register for the driver class before using it in the program. Let’s see the syntax first.

Syntax

<property name = "hibernate.connection.url">jdbc:mysql://localhost/demo</property>

Let’s see the JDBC properties in Hibernate

  • hibernate.connection.driver_class: It specifies the JDBC driver class.
  • hibernate.connection.url: It specifies the URL of JDBC.
  • hibernate.connection.username: It specifies the database username.
  • hibernate.connection.password: It specifies the database password.
  • hibernate.connection.pool_size: It specifies the size of the maximum number of connections in the pool.
  • hibernate.connection.autocommit: It specifies the mode for the JDBC connection.

Hibernate Mapping File

Hibernate configuration file also includes the <mapping> tag which is related to the mapping file in Hibernate that we will see in the coming article of this tutorial.

Example to create Hibernate Application

In this example, we will create a simple Hibernate application where we use the following steps

  • Create a java project.
  • add jar files.
  • create a database and table in MYSQL.
  • Create a POJO class.
  • Create the mapping files.
  • Create the configuration files.
  • Create a class for retrieving and storing objects.

For creating Java project and add Jar files refer to this article Environment Set up for Hibernate.

Create a Database and Table in MySQL-Write the following query

<-------Database create------>
mysql>create database demo;
<-------Use demo database------------->
mysql>use demo;
<-------create Table--------->
mysql>CREATE TABLE `demo_c` (
  `id` int NOT NULL,
  `fname` varchar(45) DEFAULT NULL,
  `lname` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

Create a Persistence class/POJO class. (We will discuss this in the coming tutorial)

Cricketer.java

public class Cricketer {
  private int id;
  private String fname;
  private String lname;

  public int getId() {
    return id;
  }

  public void setId(int id) {
    this.id = id;
  }

  public String getFname() {
    return fname;
  }

  public void setFname(String fname) {
    this.fname = fname;
  }

  public String getLname() {
    return lname;
  }

  public void setLname(String lname) {
    this.lname = lname;
  }

}

Create a Mapping file for POJO class- cricketer.hbm.xml (We will discuss this file in detail in the coming tutorial)

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
  <class name="Cricketer" table="demo_c">
    <id name="id">
      <generator class="assigned"></generator>
    </id>

    <property name="fname"></property>
    <property name="lname"></property>

  </class>

</hibernate-mapping>

Create the Hibernate Configuration file-hibernate.cfg.xml (you can check it here How to configure hibernate in Java application)

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>

  <session-factory>
    <property name="hbm2ddl.auto">update</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
    <property name="connection.username">root</property>
    <property name="connection.password">khan</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver
    </property>
    <mapping resource="Cricketer.hbm.xml" />
  </session-factory>

</hibernate-configuration>

create a class for storing and retrieving objects-TestClass.java for complete detail you can check it here How to handle session in Hibernate

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class TestClass {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Cricketer cricketer = new Cricketer();
    cricketer.setId(1);
    cricketer.setFname("Rahul");
    cricketer.setLname("Dravid");
    SessionFactory factory = new Configuration().configure().buildSessionFactory();
    Session session = factory.openSession();
    session.beginTransaction();
    session.save(cricketer);
    System.out.println("added");
    System.out.println(
        "Id " + cricketer.getId() + "\nName " + cricketer.getFname() + "\nLast Name " + cricketer.getLname());
    session.getTransaction().commit();

  }

}

Now, Run the file TestClass.java and see the output on the console.

<-----OUTPUT------>
added
Id 1
Name Rahul
Last Name Dravid
<-----OUTPUT------>

Thus we have seen the Configuration in Hibernate and learned How to configure the hibernate.cfg.xml file.

In the next article of this tutorial, we will see the Mapping file in Hibernate which is hibernate.hbm.xml.