In this tutorials we are going to see how to implement a basic hibernate application with xml based configuration.

Hibernate Example:

Technologies :

  • Hibernate-core 5.0
  • Mysql 5.5.43
  • NetBeans 8.o

Setup Database:

[sql]

mysql> create database onlinetutorialspoint;

mysql> use onlinetutorialspoint;

[/sql]

Create a student table in onlinetutorialspoint databse.

[sql]

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`)
);

[/sql]

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>

Create Hibernate Configuration:

Create HibernateConnector.java, it is responsible to generate singleton session factory objects.

[java]
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();
}
}

[/java]

Create Pojo class with respect the student table.

Student.java

[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_;
}

}

[/java]

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.

[java]
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();
}
}

}

[/java]

Hibernate Client

[java]
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);
}

}

[/java]

Output :

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

Happy Learning 🙂

Download Example