Saturday , April 29 2017
Home / Hibernate / Hibernate Example

Hibernate Example

Hibernate Example with Maven

In this tutorials we are going work with Hibernate 5. As an Hibernate example we are going to implement an entire CRUD (Create, Read, Update, Delete) application with Hibernate 5 and Mysql Database.

As we are connecting with Mysql Database, it is mandatory to add mysql-connector-java unlike Oracle Database. To resolve all internal dependencies, we are implementing the Hibernate Example with maven.

For implementing the Hibernate Example we are going to use below Tools:

  • Hibernate-core 5.0
  • Mysql 5.5.43
  • NetBeans 8.0

Lets start the step by step CRUD Hibernate Example with Hibernate 5.

Setup Database:

In this tutorials we are going to connect with MySql database. To create and use the database we have to run the below commands on MySql prompt.

Create a Database with the below command.


mysql> create database onlinetutorialspoint;

mysql> use onlinetutorialspoint;

Then create a student table in onlinetutorialspoint databse. For this example one table is enough for us.


CREATE TABLE `student` (
    `id` INT(10) NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(50) NULL DEFAULT NULL,
    `rollnumber` INT(10) NULL DEFAULT NULL,
    `gender` TINYINT(4) NULL DEFAULT NULL,
    `class` VARCHAR(50) NULL DEFAULT NULL,
    `lastupdated` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
);

Well ! As far as this example database part is completed. We need to use this database in our application.

Project Structure:

HibernateExample

Project Dependencies:

pom.xml

<project ...>
    <dependencies>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.0.0.CR1</version>
        </dependency>

        <!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.1.8.Final</version>
        </dependency>
        <dependency>
            <groupId>unknown.binary</groupId>
            <artifactId>mysql-connector-java-5.1.23-bin</artifactId>
            <version>SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
</project>

Above is the pom.xml, where we can define all required maven dependencies to build the application. maven will get all dependencies along with internal dependencies for you and place them in dependencies folder.

Create Hibernate Configuration:

Create HibernateConnector.java, from which we are getting Hibernate session and doing basic configurations.

package com.onlinetutorialspoint.config;

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

public class HibernateConnector {

    private static HibernateConnector me;
    private Configuration cfg;
    private SessionFactory sessionFactory;

    private HibernateConnector() throws HibernateException {

        // build the config
        cfg = new Configuration();

        /**
         * Connection Information..
         */
        cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
        cfg.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/onlinetutorialspoint");
        cfg.setProperty("hibernate.connection.username", "root");
        cfg.setProperty("hibernate.connection.password", "123456");
        cfg.setProperty("hibernate.show_sql", "true");

        /**
         * Mapping Resources..
         */
        cfg.addResource("com/onlinetutorialspoint/pojo/Student.hbm.xml");

        sessionFactory = cfg.buildSessionFactory();
    }

    public static synchronized HibernateConnector getInstance() throws HibernateException {
        if (me == null) {
            me = new HibernateConnector();
        }

        return me;
    }

    public Session getSession() throws HibernateException {
        Session session = sessionFactory.openSession();
        if (!session.isConnected()) {
            this.reconnect();
        }
        return session;
    }

    private void reconnect() throws HibernateException {
        this.sessionFactory = cfg.buildSessionFactory();
    }
}

Create Pojo class with respect the student table.

Student.java


package com.onlinetutorialspoint.pojo;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "student", catalog = "onlinetutorialspoint"
)
public class Student implements java.io.Serializable {

    private Integer id;
    private String name;
    private Integer rollnumber;
    private Byte gender;
    private String class_;
    private Date lastupdated;

    public Student() {
    }

    public Student(String name, Integer rollnumber, Byte gender, String class_, Date lastupdated) {
        this.name = name;
        this.rollnumber = rollnumber;
        this.gender = gender;
        this.class_ = class_;
        this.lastupdated = lastupdated;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)

    @Column(name = "id", unique = true, nullable = false)
    public Integer getId() {
        return this.id;
    }

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

    @Column(name = "name", length = 50)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "rollnumber")
    public Integer getRollnumber() {
        return this.rollnumber;
    }

    public void setRollnumber(Integer rollnumber) {
        this.rollnumber = rollnumber;
    }

    @Column(name = "gender")
    public Byte getGender() {
        return this.gender;
    }

    public void setGender(Byte gender) {
        this.gender = gender;
    }

    @Column(name = "class", length = 50)
    public String getClass_() {
        return this.class_;
    }

    public void setClass_(String class_) {
        this.class_ = class_;
    }

}

Create Hibernate Mapping File:

Create hbm file with respect to student.java and student table.

Student.hbm.xml


<?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="com.onlinetutorialspoint.pojo.Student" table="student" catalog="onlinetutorialspoint">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="name" length="50" />
        </property>
        <property name="rollnumber" type="java.lang.Integer">
            <column name="rollnumber" />
        </property>
        <property name="gender" type="java.lang.Byte">
            <column name="gender" />
        </property>
        <property name="class_" type="string">
            <column name="class" length="50" />
        </property>

    </class>
</hibernate-mapping>

Create Data Access Object

Create StudentDAO.java to access the Student details.

package com.onlinetutorialspoint.dao;

import com.onlinetutorialspoint.config.HibernateConnector;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class StudentDAO {

    public List<Student> listStudent() {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            Query query = session.createQuery("from Student s");

            List queryList = query.list();
            if (queryList != null && queryList.isEmpty()) {
                return null;
            } else {
                System.out.println("list " + queryList);
                return (List<Student>) queryList;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    public Student findStudentById(int id) {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            Query query = session.createQuery("from Student s where s.id = :id");
            query.setParameter("id", id);

            List queryList = query.list();
            if (queryList != null && queryList.isEmpty()) {
                return null;
            } else {
                return (Student) queryList.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    public void updateStudent(Student student) {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            session.saveOrUpdate(student);
            session.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    public Student addStudent(Student student) {
        Session session = null;
        Transaction transaction = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            transaction = session.beginTransaction();
            session.save(student);
            transaction.commit();
            return student;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    public void deleteStudent(int id) {
        Session session = null;
        try {
            session = HibernateConnector.getInstance().getSession();
            Transaction beginTransaction = session.beginTransaction();
            Query createQuery = session.createQuery("delete from Student s where s.id =:id");
            createQuery.setParameter("id", id);
            createQuery.executeUpdate();
            beginTransaction.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

}

Hibernate Client

Create a client class, from which we can access the StudentDAO.java to make CRUD operations.

package com.onlinetutorialspoint.service;

import com.onlinetutorialspoint.dao.StudentDAO;
import com.onlinetutorialspoint.pojo.Student;
import java.util.List;

public class DbOperations {

    StudentDAO studentDAO = new StudentDAO();

    public static void main(String[] args) {
        DbOperations dbOperations = new DbOperations();
        Student createStudent = dbOperations.createStudent();

        List<Student> studentList = dbOperations.getStudentList();
        if (studentList != null) {
            for (Student student : studentList) {
                System.out.println("Student Name : " + student.getName());
            }
        }
        dbOperations.updateStudent(createStudent.getId());
        Student student = dbOperations.getStudent(createStudent.getId());
        if (student != null) {
            System.out.println("Student Details After Updation : " + student.getName());
        }

        dbOperations.deleteStudent(createStudent.getId());

    }

    public Student createStudent() {
        Student s = new Student();
        s.setGender(new Byte("1"));
        s.setName("John");
        s.setClass_("12");
        s.setRollnumber(007);
        studentDAO.addStudent(s);
        return s;
    }

    public void updateStudent(Integer id) {
        Student student = studentDAO.findStudentById(id);
        student.setName("online tutorials point");
        studentDAO.updateStudent(student);
        System.out.println("Student Updated Success");
    }

    public void deleteStudent(Integer id) {
        studentDAO.deleteStudent(id);
        System.out.println("Student Deleted Success");
    }

    public List<Student> getStudentList() {
        return studentDAO.listStudent();
    }

    public Student getStudent(Integer id) {
        return studentDAO.findStudentById(id);
    }

}

Output :

Student Name : John
Student Updated Success
Student Details After Updation : online tutorials point
Student Deleted Success

Download Example

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Hibernate Projection with Example

In this tutorials, we are going to learn about Hibernate Projection with a simple example. …

Leave a Reply

Your email address will not be published. Required fields are marked *