Hibernate - Hello, World! using XML Mapping

This tutorial explains you, how to develop a simple database application using Hibernate Object Relational Mapping (ORM) framework and MySQL database. This article uses XML mappings; the annotation mapping is explained in: Hibernate - Hello, World! using Annotation Mapping

You need Eclipse for Java EE developers and MySQL server in your system in-order to try this tutorial.
If you prefer to import the necessary libraries manually as shown in "Step 3 Without Maven", Eclipse for Java developers is enough. Those who prefer Maven projects, need to have M2Eclipse plugin in their Eclipse. This tutorial recommends Eclipse for Java EE, since it has M2Eclipse plugin by default. Also please be informed that the project attached at the end of this tutorial is created using Maven.
Step 1:
Create a database “javahelps” and a table “student” in MySQL.
CREATE DATABASE IF NOT EXISTS javahelps;

CREATE  TABLE javahelps.student ( 
student_id INT NOT NULL ,
student_name VARCHAR(45) NOT NULL ,
student_age INT NOT NULL ,
PRIMARY KEY (student_id) );


Step 2:
Create a new Java project “HibernateXML” in Eclipse.


Step 3:
This step has two choices. You can either, convert this project to a Maven project or continue as an ordinary Java project.

With Maven:
Step 3.1:
Convert the project to Maven project by right clicking on the project and selecting Configure → Convert to Maven Project.


Step 3.2:
Give the group id: “com.javahelps” and artifact id: “HibernateXML” in the appeared dialog and Finish the process.


Step 3.3:
Add the following dependencies to pom.xml.
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.3.10.Final</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.12</version>
</dependency>

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.20.0-GA</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.36</version>
</dependency>

After the modification, pom.xml should look like this:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javahelps</groupId>
    <artifactId>HibernateXML</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.20.0-GA</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.36</version>
        </dependency>
    </dependencies>
</project>

Without Maven:
Step 3.1:
Download and extract the Hibernate libraries, from this link: Hibernate ORM.
Download and extract the MySQL JDBC connector, from this link: Download Connector/J

Step 3.2:
Create a new folder “lib” in the project.


Step 3.3:
Copy all the *.jar files from “hibernate-release-xxx/lib/required” folder and paste them into the “lib” folder.
Also, copy the mysql-connector-java-xxx-bin.jar file to "lib" folder of your project.

Step 3.4:
Select all the libraries; right click on them and select Build Path → Add to Build Path



After adding to Build Path, the libraries have to be listed under Referenced Libraries as shown below:


Step 4:
Create a new package “com.javahelps.hibernate

Step 5:
Create a new class Student inside the package as shown below.
package com.javahelps.hibernate;

import java.io.Serializable;

public class Student implements Serializable {
    private int id;
    private String name;
    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return id + "\t" + name + "\t" + age;
    }
}

Step 6:
Right click on the project and select New → Source Folder.



Give the folder name as “resources' and click on the “Finish” button in the appeared dialog.



Step 7:
Create a new file Student.hbm.xml, in the resources folder and modify the content as shown below.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <!-- class name is the fully qualified name of the POJO class -->
    <!-- table is the name of the database table which represents the Student -->
    <class name="com.javahelps.hibernate.Student" table="student">
        <!-- Attribute id is mapped to the column student_id -->
        <id name="id" type="integer">
            <column name="student_id" />
        </id>

        <!-- Attribute name is mapped to the column student_name -->
        <property name="name" type="string">
            <column name="student_name" length="10" not-null="true" />
        </property>

        <!-- Attribute age is mapped to the column "student_age" -->
        <property name="age" type="integer">
            <column name="student_age" length="20" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

Step 8:
Create a new file hibernate.cfg.xml, in the resources folder and modify the content as shown below.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <!-- Create table if not exists -->
        <property name="hibernate.hbm2ddl.auto">update</property>
        <!-- The JDBC driver of your database -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <!-- Indicate the database to generate suitable SQL -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- The JDBC URL to the database instance -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javahelps</property>
        <!-- The database username -->
        <property name="hibernate.connection.username">root</property>
        <!-- The database password -->
        <property name="hibernate.connection.password">root</property>
        <!-- XML mapping file -->
        <mapping resource="Student.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>
In this configuration file, change the username and password of the database according to your database.

Step 9:
Create a new Java class Main.java with main method.

Step 10:
Add a static variable SessionFactory and initialize it using a static initialization block.
package com.javahelps.hibernate;

import java.util.Properties;

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

public class Main {
    // Create the SessionFactory when you start the application.
    private static final SessionFactory SESSION_FACTORY;

    /**
     * Initialize the SessionFactory instance.
     */
    static {
        // Create a Configuration object.
        Configuration config = new Configuration();
        // Configure using the application resource named hibernate.cfg.xml.
        config.configure();
        // Extract the properties from the configuration file.
        Properties prop = config.getProperties();

        // Create StandardServiceRegistryBuilder using the properties.
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
        builder.applySettings(prop);

        // Build a ServiceRegistry
        ServiceRegistry registry = builder.build();

        // Create the SessionFactory using the ServiceRegistry
        SESSION_FACTORY = config.buildSessionFactory(registry);
    }

    public static void main(String[] args) {

    }
}

Step 11:
Add the CRUD methods to the Main class and access them from the main method as given below:
package com.javahelps.hibernate;

import java.util.List;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class Main {
    // Create the SessionFactory when you start the application.
    private static final SessionFactory SESSION_FACTORY;

    /**
     * Initialize the SessionFactory instance.
     */
    static {
        // Create a Configuration object.
        Configuration config = new Configuration();
        // Configure using the application resource named hibernate.cfg.xml.
        config.configure();
        // Extract the properties from the configuration file.
        Properties prop = config.getProperties();

        // Create StandardServiceRegistryBuilder using the properties.
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
        builder.applySettings(prop);

        // Build a ServiceRegistry
        ServiceRegistry registry = builder.build();

        // Create the SessionFactory using the ServiceRegistry
        SESSION_FACTORY = config.buildSessionFactory(registry);
    }

    public static void main(String[] args) {
        // Create two Students
        create(1, "Alice", 22); // Alice will get an id 1
        create(2, "Bob", 20); // Bob will get an id 2
        create(3, "Charlie", 25); // Charlie will get an id 3

        // Update the age of Bob using the id
        upate(2, "Bob", 25);

        // Delete the Alice from database
        delete(1);

        // Print all the Students
        List<Student> students = readAll();
        if (students != null) {
            for (Student stu : students) {
                System.out.println(stu);
            }
        }

        // NEVER FORGET TO CLOSE THE SESSION_FACTORY
        SESSION_FACTORY.close();
    }

    /**
     * Create a new Student.
     *
     * @param name
     * @param age
     */
    public static void create(int id, String name, int age) {
        // Create a session
        Session session = SESSION_FACTORY.openSession();
        Transaction transaction = null;
        try {
            // Begin a transaction
            transaction = session.beginTransaction();
            Student stu = new Student();
            stu.setId(id);
            stu.setName(name);
            stu.setAge(age);
            // Save the student
            session.save(stu);
            // Commit the transaction
            transaction.commit();
        } catch (HibernateException ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the session
            session.close();
        }
    }

    /**
     * Read all the Students.
     *
     * @return a List of Students
     */
    public static List<Student> readAll() {
        List<Student> students = null;
        // Create a session
        Session session = SESSION_FACTORY.openSession();
        Transaction transaction = null;
        try {
            // Begin a transaction
            transaction = session.beginTransaction();
            students = session.createQuery("FROM Student").list();
            // Commit the transaction
            transaction.commit();
        } catch (HibernateException ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the session
            session.close();
        }
        return students;
    }

    /**
     * Delete the existing Student.
     *
     * @param id
     */
    public static void delete(int id) {
        // Create a session
        Session session = SESSION_FACTORY.openSession();
        Transaction transaction = null;
        try {
            // Begin a transaction
            transaction = session.beginTransaction();
            // Get the Student from the database.
            Student stu = (Student) session.get(Student.class, Integer.valueOf(id));
            // Delete the student
            session.delete(stu);
            // Commit the transaction
            transaction.commit();
        } catch (HibernateException ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the session
            session.close();
        }
    }

    /**
     * Update the existing Student.
     *
     * @param id
     * @param name
     * @param age
     */
    public static void upate(int id, String name, int age) {
        // Create a session
        Session session = SESSION_FACTORY.openSession();
        Transaction transaction = null;
        try {
            // Begin a transaction
            transaction = session.beginTransaction();
            // Get the Student from the database.
            Student stu = (Student) session.get(Student.class, Integer.valueOf(id));
            // Change the values
            stu.setName(name);
            stu.setAge(age);
            // Update the student
            session.update(stu);

            // Commit the transaction
            transaction.commit();
        } catch (HibernateException ex) {
            // If there are any exceptions, roll back the changes
            if (transaction != null) {
                transaction.rollback();
            }
            // Print the Exception
            ex.printStackTrace();
        } finally {
            // Close the session
            session.close();
        }
    }
}

Step 12:
Run the project and check the output.

If you have any problems in executing this project, feel free to comment below your problem.

Find the Maven project at Git Hub.
Previous
Next Post »

Contact Form

Name

Email *

Message *