Hibernate: sample application with MySQL

As a continuation of the previous article, I want to demonstrate a simple example of Hibernate usage. I will show you the basic principles of Hibernate functionality. The article will cover annotation based configurations. For the tutorial you need to have installed an IDE (e.g. Eclipse), Maven, m2e plugin, MySQL.

At the beginning I create a simple Java project and convert it to maven project. Then in the pom.xml I add these dependencies:

		
			org.hibernate
			hibernate-core
			4.1.9.Final
		
		
			mysql
			mysql-connector-java
			5.1.22
		

Hibernate is an essential library in the tutorial. MySQL connector is needed in order to establish connection with the database.

As the result you will get something like this:

hibernate-project-structure-at-start

Now it’s a good time to think about the java classes which are required for the demonstration of Hibernate functionality. The example will be based on interaction with one database table. Hence I will create one POJO class to represent the database table and I’m going to annotate it. One Java class is needed for generation of SessionFactory. And in the end I suggest you create several classes for the demonstration of CRUD operations using Hibernate.
But firstly I will create a hibernate.cfg.xml in the src folder:




    
        com.mysql.jdbc.Driver
        root
        root
        jdbc:mysql://localhost:3306/hibnatedb
        org.hibernate.dialect.MySQLInnoDBDialect
    	true 
    	1
    	
    	

    

I hope the code snippet above doesn’t need any explanation because it’s really clear and self commented. But as usual you are welcome to ask any question in the comments.
Afterwards let’s create HibernateUtil class. Its destination is to be a helper class, which contains an initialization of the SessionFactory.

package com.hib.init;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	
	private static final SessionFactory sessionFactory;
	private static final ServiceRegistry serviceRegistry;
	
	static {
		Configuration conf = new Configuration();
		conf.configure();
		serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
		try {
			sessionFactory = conf.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			System.err.println("Initial SessionFactory creation failed." + e);
			throw new ExceptionInInitializerError(e);
		}		
	}
	
	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

Here occurs initialization of SessionFactory based on hibernate.cfg.xml; You can notice that static block is present because often just one SessionFactory object is used within application.

Here is a code snippet for the creation of table in the database:

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(20) NOT NULL,
  `age` int(2) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

This database table, as you remember must have an appropriate POJO class.

package com.hib.entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class Student {
	
	@Id
	@GeneratedValue
	private Integer id;
	
	private String firstName;
	private Integer age;
	
	public Student() {};
	
	public Student(Integer id, String firstName, Integer age) {
		this.id = id;
		this.firstName = firstName;
		this.age = age;
	}
	
        //Here you need to generate getters and setters

}

Pay your attention to the fact that I have imported annotations from javax.persistence.* package, that’s because we can work with Hibernate through JPA. Notice that the class above is figured in the hibernate.cfg.xml. I recommend you read more about these annotations in the official documentations, there you will find additional important information about them.

It’s time to perform CRUD operations with all this stuff.

package com.hib.demo;

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

import com.hib.entities.Student;
import com.hib.init.HibernateUtil;

public class DemoFirst {

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Student student = new Student();
		student.setFirstName("Bob");
		student.setAge(26);
		
		session.save(student);
		session.getTransaction().commit();
		
		session.close();

	}
}

Run this class several times and add different students to the table.
After that try to run this class:

package com.hib.demo;

import java.util.List;

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

import com.hib.entities.Student;
import com.hib.init.HibernateUtil;

public class DemoSecond {

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		
		List students = session.createQuery("from Student").list();
		
		session.close();
		
		for (Student st : students) {
			System.out.println(st.getId()+". "+st.getFirstName()+" "+st.getAge());
		}
	}
}

In this way you can perform select statements using Hibernate.
To update statements is not harder than previous operations:

package com.hib.demo;

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

import com.hib.entities.Student;
import com.hib.init.HibernateUtil;

public class DemoThird {

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Student student = (Student) session.get(Student.class, 1);
		student.setFirstName("Zet");
		student.setAge(45);
		
		session.update(student);
		session.getTransaction().commit();
		
		session.close();
	}
}

In the end it’s time to try delete operation:

package com.hib.demo;

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

import com.hib.entities.Student;
import com.hib.init.HibernateUtil;

public class DemoFourth {

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		
		Student student = (Student) session.get(Student.class, 1);
		
		session.delete(student);
		session.getTransaction().commit();
		
		session.close();

	}
}

End view of the project:

end-view-of-hibernate-project

Summary

Hibernate is very useful, it takes plenty of work on itself. The main aim of Hibernate is to make development more easy and convenient. You can’t imagine all range of Hibernate functionality from this post, but it’s a good point from which you can start your learning.

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
  • http://codeguide.hu David Csejtei

    Hi Alexey,

    This is a very useful post, it helps understanding the basic concept of the Hibernate. Thank you.

    Keep it up!

  • Ahmed

    very interesting ,Thank you !

  • Yusuf Ibr.

    Hi, I wanna ask you something related to this article,

    student.setFirstName(“Zet”);

    and
    student.student.setFirstName(“Bob”);

    why i cannot find setFirstName function in Student class function ?

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Look at the Student class, and find place with a commented line. You can find there information that every class fied need to have getter and setter method.

  • Pol

    Can you share the project zip file.

    • http://fruzenshtein.com/ Alex Zvolinskiy

      Hi

      Currently I don’t have the project’s files

  • coollanka

    pls share project file