Hibernate in 10 minutes


Hibernate is a quick way to store / retrieve data to a database.

Step 1. Download all necessary files

Download MySQL from mysql.com → downloads → MySQL Community Server → Windows ZIP/Setup.EXE (x86) → Pick a mirror → No thanks, just take me to the downloads → Greece [National Technical University of Athens] HTTP → mysql-5.0.51b-win32.zip

Download JDBC driver of MySQL from mysql.com → downloads → Connectors → Connector/J → Source and Binaries (zip) → Pick a mirror → No thanks, just take me to the downloads → Greece [National Technical University of Athens] HTTP → mysql-connector-java-5.1.6.zip

Download Hibernate core from hibernate.org → Download → Hibernate Core → Download → hibernate-3.2.6.ga.zip

Download Hibernate annotations from hibernate.org → Download → Hibernate Annotations → Download → hibernate-annotations-3.3.1.GA.zip

Step 2. Make the database schema

ΜySQL is easily installed. After the installation completes, a configuration wizard opens: you should note down the root password.

In order to start MySQL go to Start → Programs → MySQL → MySQL Server 5.0 → MySQL Command Line Client → give the root password.

Write CREATE DATABASE heat;

For confirmation state show databases; and then use heat;

It would be useful to leave the command prompt window of MySQL open.

So, you have just created the database schema. What about the tables? Well, Hibernate will make them automatically!

Step 3. Concentrate all jars

Create a folder, e.g. C:/jars and copy inside:

  • hibernate-3.2.6.ga.zip/hibernate3.jar
  • everything that lies inside hibernate-3.2.6.ga.zip/lib
  • hibernate-annotations-3.3.1.GA.zip/hibernate-annotations.jar
  • hibernate-annotations-3.3.1.GA.zip/lib/hibernate-commons- annotations.jar and ejb3-persistence.jar
  • the JDBC driver mysql-connector-java-5.1.6.zip/mysql-connector- java-5.1.6-bin.jar

Step 4. Create the actual project.

Create a project with the name “Hibernate” using Eclipse or any other IDE (NetBeans, JDeveloper etc).

Add the folder with the jars into the classpath: Project → Properties → Java Build Path → Add External JARs…

Step 5. Write hibernate.cfg.xml

hibernate.cfg.xml is a special file used by Hibernate. It holds information about the database we are using.

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

<hibernate-configuration>
   <session-factory>
      <!-- Database connection settings -->
      <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="connection.url">jdbc:mysql://localhost/heat</property>
      <property name="connection.username">root</property>
      <property name="connection.password">12345</property>

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

      <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
      <property name="current_session_context_class">thread</property>

      <!-- Echo all executed SQL to stdout -->
      <property name="show_sql">true</property>
   </session-factory>
</hibernate-configuration>

The properties connection.* hold information that is directly used in JDBC code (Class.forName() etc.). Make sure you enter the correct password!

SQL dialect is an interesting property: We say to Hibernate that it communicates with a MySQL database.

Place hibernate.cfg.xml inside the folder of the project, e.g. inside C:/Eclipse/workspace/Hibernate, or anywhere in the classpath. This file must be in the classpath.

Step 6. Build the model

This simple application handles persons. For every person, we are interested about the name and a unique number (identifier).

class: Person

state: Long id, String name

behaviour: setId(), getId(), setName(), getName()

	public class Person {

	private Long id;
	private String name;

	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

So, it’s a simple java bean. What we would be pottering about now is creating 1. a table “person” in the database and 2. a class with pure JDBC: insert(Person person), select(Long id), update(Person person), delete(Long id) etc. Fortunately, Hibernate takes care of both of these tasks. We just use some annotations straight from the Java Persistence API.

import javax.persistence.*;

@Entity
public class Person {

	private Long id;
	private String name;

	@Id
	@GeneratedValue
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

}

@Entity means that all the objects that derive from this class can be stored to the database.

@id declares the primary key.

@GeneratedValue means that the database will ensure the uniqueness of the primary key. (In MySQL is the AUTO_INCREMENT flag)

Step 7. Time for action

Create the table person in the database

	// usual initialization
	AnnotationConfiguration config = new AnnotationConfiguration();
	config.addAnnotatedClass(Person.class);
	config.configure();

	// create the table in the database
	new SchemaExport(config).create(true, true);

During the usual initialization the class Person is added config.addAnnotatedClass(Person.class);. After that, all configuration parameters are read from hibernate.cfg.xml and all classes marked with an @Entity are configured config.configure();. These statements naturally belong to a constructor.

The statement new SchemaExport(config).create(true, true); creates the tables in the database. In case these tables are already defined, they get dropped and recreated; all their data are lost.

To confirm write show tables; at the MySQL command prompt.

Store an object in the database

	// usual initialization
	AnnotationConfiguration config = new AnnotationConfiguration();
	config.addAnnotatedClass(Person.class);
	config.configure();

	// we want to store Vincent Hanna to the database
	Person person = new Person();
	person.setName("Vincent Hanna");

	// expensive initialization
	SessionFactory factory = config.buildSessionFactory();
	// get session
	Session session = factory.getCurrentSession();
	
	// store
	session.beginTransaction();
	session.save(person);
	session.getTransaction().commit();

The statement SessionFactory factory = config.buildSessionFactory(); costs a lot. That’s why the factory object should be created once and be made available to the rest of the application (e.g. singleton pattern).

To confirm write SELECT * FROM person; at the MySQL command prompt.

You may use a class with utility static methods to tidy things up:

	// we want to store Vincent Hanna to the database
	Person person = new Person();
	person.setName("Vincent Hanna");
	DataBase.save(person);

Conclusion: We gain precious development time as it is no more necessary 1. to manually create any table in the database and 2. to write long JDBC classes with the usual operations (insert, update, select, delete).

8 Responses to Hibernate in 10 minutes

  1. LomiQuigumS says:

    Hello my friends🙂 😉

  2. toupil says:

    I use hibernate/mysql on my website http://www.toupil.fr and i appreciate this technology. tank you for your article.

  3. nikosjava says:

    Bravo, your site is really cool!

  4. maneesh kumar sinha says:

    Very nice tutorial.
    One question
    Can we handle auto increment (mysql) using annotation without declaring primary key as auto increment.? In other words what could be replacement /equivalent for in my entity calss

  5. Nuno says:

    I really appreciate your blog.
    This is really useful and there should be more articles like this one on other subjects, ideally one single place where we could find similar summaries for other technologies.

    Well done!

  6. helotest says:

    Wonderful and complete detail. Truly appreciate it and Thank You.

  7. […] Hibernate in 10 mins Share this:TwitterFacebookLike this:LikeBe the first to like this. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: