ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to create / setup a successful Hibernate project using Eclipse and test the project?

Updated on December 16, 2013

Hibernate is an ORM (object/relational mapping) tool for Java environments. Before using Hibernate, we must have to create a hibernate project. Creation of hibernate project is not so easy and not so difficult. The thing which must be careful is that to forward step by step like create an new project, adding necessary libraries, creating session factory and creating the main program. This tutorial will focus you the step by step solution to create a new Hibernate project and to test the hibernate project whether it is running successfully or not. Hopefully, completing the steps of this tutorial, you will able to create your own hibernate project and run it successfully.

Note: To complete this tutorial, we need a database without any table. You can create a database easily. How to create a database is skipped here.

Steps to create / setup a successful Hibernate project using Eclipse and test the project

Steps to create / setup a successful Hibernate project using Eclipse and test the project, we need to complete the following five steps:

Step 1: Creating a Java Project
Step 2: Adding necessary jars
Step 3: Creating a package
Step 4: Creating Hibernate configuration file
Step 5: Creating the Session Factory
Step 6: Testing out the configuration

The details of each step are explained with codes in the following sections:

Step 1: Creating a Java Project

To create a hibernate project, we firstly have to create a Java project. We will use Eclipse to complete this tutorial. However, if you are using Spring Tool Suite, the tutorial will work as usual. To create a new project, do the following steps:

  1. Open Eclipse in your computer. Eclipse works same both for Windows and Linux operatin system.
  2. Click on File menu
  3. Click on New when the file menu will be expanded
  4. Click on Java Project to start the java project

5. Type a project name as you like. For this tutorial, we named it as HibernateProject.

7. Choose the location where do you need to save the project. We choose the default location. And we checked the option Use default location. You may choose your desired location from Browser... option.

8. Choose the version of executable environment JRE which you would like to use. For this example, we use JavaSE-1.7 version

9. It's good to separate the sources and class files.
We can configure this using the option Create separate folders for sources and class files.

10. Click on Next button for the next step.

11. We have to choose the source folder of all java files. We click on Source and make sure that the src folder is selected there.

12. Choose the output folder location from the Default output folder option

13. Click on Finish button to create the Java project for our hibernate tutorial..

When you have successfully completed the above steps, you will find the following structure in you Eclipse window.

Step 2: Adding necessary jars

In this step, we have to add necessary jars. To do this, we do the following steps:

1. Create a new folder into HibernateProject and named it as libs.

2. Go to official page of Hibernate using the link http://hibernate.org/. Now, download hibernate.

3. After the completion of download, extract the hibernate download files.

4. From the extracted folder, choose the following jars and copy them into the libs folder.

5. Choose all of the jars and right click on them after selecting those and choose Build Path option and the option will be expanded. You will see a new option Add to Build Path.

6. Click on Add to Build Path option.

7. You will see a new folder will be created with the name Referenced Libraries. Click on that folder and it will be expanded. You will see all the reference jars are added into your Hibernate project.

8. We also need to download another jar for the database connectivity. The connector of database varies. In this tutorial, we will use MySQL database. So,we will download MySQL JDBC connector form the link http://dev.mysql.com/downloads/connector/.

9. After downloading the connector, we will copy the jar to our libs and again add that to our Reference libraries folder.

Step 3: Creating a package

We will store all our java files by packagewise. We we need to create a package. To create a package do the followings:

1. Right click on the src folder form our HibernateProject.

2. Choose New option and it will be expanded

3. From the expanded option, choose Package option.


4. Type a package name. For our example, we named our package like com.hubpages.plusminus

5. Click on Finish button to complete the package creation to our hibernate projcet.

After completing the above steps, you will see a package is created into your hibernate project like the following picture.

Step 4: Creating Hibernate configuration file

It's time to create the configuration file for our Hibernate project. It's very easy to do this. Follow the following steps:

1. Click on File menu and it will be expanded.

2. Choose New from the expanded menu and choose Others

3. Choose Hibernate Configuration File (cfg.xml) and click on Next to start creating hibernate configuration file

4. Choose the parent folder to put the hibernate configuration file. To do this choose the src folder form the project

5. Type the configuration file name like hibernate.cfg.xml

6. Click on Next button

7. In this wizard, you have to configure everything. Right now, just keep blank in the Session factor name field.

8. Choose the database type from the drop down list of Database dialect select box. We are using MySQL database for this tutorial. So, we choose MySQL from the Database dialect option.

9. Choose the appropriate Driver class. We choose com.mysql.jdbc.Driver form the Driver class option.

10. Type the connection URL into the Connection URL field. For this tutorial, we type jdbd:mysql://localhost:3306. Here, 3306 is the port number.

11. Type the database name in the Default Schema field. We have a database named as mydb and so, we typed that into Default Schema field.

12. Type the database username and password into the Username and Password filed. If there is no password then keep the filed empty.

13. Now click on Finish button

When you have completed all the above steps, your configuration file is ready to use. The full configuration file code is like the following:

hibernate.cfg.xml

<?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>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.default_schema">mydb</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
 </session-factory>
</hibernate-configuration>

Step 5: Creating the Session Factory

In this step, we have to create Session Factory. To do this follow the following steps:

1.Create a new class into com.hubpages.plusminus package

2. Name the class as HibernateUtilites

3. Uncheck the option public static void main(String[] args) if it is checked.

4. Click on Finish button

5. Write the following lines of code into the HibernateUtilites file.

Private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	static {
		try {
			Configuration configuration = new Configuration().configure();

			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (HibernateException exception) {
			System.out.println("Problem creating session factory");
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

The full code of HibernateUtilities will look like the followings:

HibernateUtilities.java

package com.hubpages.plusminus;

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

public class HibernateUtilities {

	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	static {
		try {
			Configuration configuration = new Configuration().configure();

			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (HibernateException exception) {
			System.out.println("Problem creating session factory");
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

}

Step 6: Testing out the configuration

We are now ready to start testing our code which we just created. Follow the following steps to test and run the code:

1. Create a new class into com.hubpages.plusminu package

2. Name the class as MainProgram

3.Check the check box with the option public static void main(String[] args)

4. Click on Finish button.

After following the above steps, you will find the code into your MainProgram.java file.

package com.hubpages.plusminus;

public class MainProgram {

	public static void main(String[] args) {

	}

}

5. Now, create a session and open the session and at last close the session using the following line of codes:

System.out.println("Hibernate project");

		Session session = HibernateUtilities.getSessionFactory().openSession();
		session.close();

The full code will look like the following:

MainProgram.java

package com.hubpages.plusminus;

import org.hibernate.Session;

public class MainProgram {

	public static void main(String[] args) {

		System.out.println("Hibernate project");

		Session session = HibernateUtilities.getSessionFactory().openSession();
		session.close();

	}
}

6. Run the program in Eclipse using the arrow button

If everything is correct, you will find the following type of output without any error.

Hibernate Project
Dec 15, 2013 3:59:15 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.2.Final}
Dec 15, 2013 3:59:15 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.2.8.Final}
Dec 15, 2013 3:59:15 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Dec 15, 2013 3:59:15 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Dec 15, 2013 3:59:15 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Dec 15, 2013 3:59:15 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Dec 15, 2013 3:59:15 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Dec 15, 2013 3:59:15 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Dec 15, 2013 3:59:16 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Dec 15, 2013 3:59:16 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Dec 15, 2013 3:59:16 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Dec 15, 2013 3:59:16 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306]
Dec 15, 2013 3:59:16 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root}
Dec 15, 2013 3:59:17 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 15, 2013 3:59:17 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 15, 2013 3:59:17 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory

And that's all. Following the above steps, you can easily create a hibernate project completely. If you find any error, read the error and try to fix. If you are unable to fix then you may mention it in the comment section and you may get a solution. In the next tutorials, we will try to use real database to manipulate data like insert / update / delete etc.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Anton 14 months ago

      Thank you so much. It is a very good guide!

    Click to Rate This Article