Home Hibernate Hibernate4.2 Hibernate Example Step by Step in Eclipse
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Hibernate Example Step by Step in Eclipse

Advertisement
In this Hibernate tutorial section you will learn how to create first Hibernate example step-by-step in Eclipse. The Eclipse IDE is very helpful in creating and running Hibernate example program easily and quickly.

Hibernate Example Step by Step in Eclipse  - The easiest way of getting started with the development of application in Hibernate

Here I will provide you step-by-step tutorial of creating first example in Hibernate 4.2. We have used MySQL Database for developing the tutorial. MySQL is free database which works well with the Hibernate framework. If you have other database you just change few settings in the xml file and connect to your database.

Steps to create the example program

Follow the following easy steps and create you hibernate based applications.

Step 1: Setup the MySQL database

Download the MySQL database and then setup of your computer. Note down the user name, password and port number of MySQL database. Check the tutorial: Installing MySQL on Windows if you don't know how to install MySQL databse.

After installing MySQL database you should create database and table in the database.

Step 2: Creating database and table

Connect to MySQL server using any IDE or command line tool. Use the following query to create database:

create database hibernate4;

Now you should connect to database using following sql:

mysql> connect hibernate4;
Connection id:    3
Current database: hibernate4

mysql>

Use the following query to create the table:

CREATE TABLE `employee` (                      
            `id` int(11) NOT NULL AUTO_INCREMENT,        
            `emp_name` varchar(100) DEFAULT NULL,        
            `emp_address` varchar(500) DEFAULT NULL,     
            `emp_mobile_nos` varchar(100) DEFAULT NULL,  
            PRIMARY KEY (`id`)                           
          )

Step 3: Download the Hibernate 4.2.x framework.

Check the tutorial Setup Hibernate Environment,  which will explain you how you can download and setup the environment.

Step 4: Create a new project in Eclipse.

To create a new project select new project and select Java Project as shown below:

Hibernate 4 Example

Select the project location and click on the "Next" button.

Hibernate 4 Example

Then click on the "Finish" button. Eclipse will create the new project for you.

Step 5: Add libraries files

Now we will add the libraries file in the project. Create a new directory lib by selecting new-> folder from the menu as shown below:

Hibernate 4 Example

Enter the name of the folder e.g. "lib" as shown below:

Hibernate 4 Example

Eclipse will create a new folder as shown below:

Hibernate 4 Example

Now copy the libraries from the "lib/required" directory of the Hibernate 4.2.8 downloads. Here is the screen shot showing the libraries files:

Hibernate 4 Example

 

Hibernate 4 Example

Select the project properties as shown below:

Hibernate 4 Example

Go to the "Java Build Path" -> "Libraries" as shown below and click on "Add JARs":

Hibernate 4 Example

Select all the JAR's from the lib directory as shown below:

Hibernate 4 Example

Finally click on the "OK" button to complete the process as shown below:

Hibernate 4 Example

Following screen shows the list of jar files added into the project.

Hibernate 4 Example

Similarly add the mysql-connector-java-5.1.27-bin.jar file into your project and then add it to the "Java Build Path".

Step 6: Create model class (Employee.java)

Create a new package net.roseindia.model and then add a new Java file named "Employee.java".  Following screen shot shows how to create a package in Eclipse IDE.

Hibernate 4 Example

Enter the name of package and then click "Finish" button. Eclipse will create a new package as shown below:

Hibernate 4 Example

Create a new file as shown below:

Hibernate 4 Example

You should add the following code in the "Employee.java" file:

package net.roseindia.model;
import java.io.Serializable;

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

import javax.persistence.Table;
/**
 * @author Deepak Kumar
 * Web: http://www.roseindia.net
 */
@Entity
@Table(name = "employee")
public class Employee implements Serializable{

	@Id
	@GeneratedValue
	@Column(name="id")
	private int id;	

	@Column(name="emp_name")
	private String empName;

	@Column(name="emp_address")
	private String empAddress;	  

	@Column(name="emp_mobile_nos")
	private String empMobileNos;

	public int getId() {
		return id;
	}

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

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getEmpAddress() {
		return empAddress;
	}

	public void setEmpAddress(String empAddress) {
		this.empAddress = empAddress;
	}

	public String getEmpMobileNos() {
		return empMobileNos;
	}

	public void setEmpMobileNos(String empMobileNos) {
		this.empMobileNos = empMobileNos;
	}

}

Above file id annotated with the JPA annotations and maps the entity with the "employee" table of the database.

We have used following annotations in the model class:

org.hibernate.annotations.Table: for mapping it to a table

javax.persistence.Column: for mapping the entity field with the table column

javax.persistence.Entity: for specifying a class as an entity class

javax.persistence.GeneratedValue: primary key generation strategy.

javax.persistence.Id: The primary key of the entity

javax.persistence.Table: for mapping it to the database table

Step 7: Add the hibernate.cfg.xml file to the project. Create a new file "hibernate.cfg.xml" in the src folder of the project as shown below:

Hibernate 4 Example

Add the following into the hibernate.cfg.xml file:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//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/hibernate4</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>

<mapping class="net.roseindia.model.Employee" />

</session-factory>
</hibernate-configuration>

Step 8: Add MySQL Driver library

Download the latest MySQL JDBC driver from http://dev.mysql.com/downloads/connector/j/ and then add the mysql-connector-java-5.1.27-bin.jar file into the project lib directory.  Also add this jar file into java build path.

Step 9: Add the Java file for initializing the Hibernate ORM

Create a new Java file named "HibernateUtil.java" as shown below:

Hibernate 4 Example

Here is the code of the Java file which is used to initialize the ORM environment and returns the SessionFactory object to the application:

package net.roseindia;

import org.hibernate.SessionFactory;

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

/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */
public class HibernateUtil {
	private static final SessionFactory sessionFactory;

	private static ServiceRegistry serviceRegistry;

	static {

		try {

			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(
					configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);

		} catch (Throwable th) {

			System.err.println("Enitial SessionFactory creation failed" + th);

			throw new ExceptionInInitializerError(th);

		}

	}

	public static SessionFactory getSessionFactory() {

		return sessionFactory;

	}
}

We will use the getSessionFactory() method to get the SessionFactory object in our application.

Step 10: Testing the application.

Now we are ready to test the application. Create a new file CreateData .java and then add the following code in it:

package net.roseindia;

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

import net.roseindia.model.*;
/**
 * @author Deepak Kumar 
 * Web: http://www.roseindia.net
 */
public class CreateData {
	public static void main(String[] args) throws Exception {

		SessionFactory sessFact = HibernateUtil.getSessionFactory();
		Session session = sessFact.getCurrentSession();
		org.hibernate.Transaction tr = session.beginTransaction();
		Employee emp = new Employee();
		emp.setEmpName("Deepak Kumar");
		emp.setEmpMobileNos("000000");
		emp.setEmpAddress("Delhi - India");
		session.save(emp);
		tr.commit();
		System.out.println("Successfully inserted");
		sessFact.close();
	}

}

Here we are getting the Session object from the SessionFactory and uses the save method to save the Employee object. The save method actually instructs the hibernate to create the insert statement and then execute it against the database. Here is the output of the program:

INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Dec 19, 2013 12:04:39 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Dec 19, 2013 12:04:39 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory 
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into employee (emp_address, emp_mobile_nos, emp_name) values (?, ?, ?)
Successfully inserted

In this section you have created first program in Hibernate which inserts the data into database.

Check more Hibernate 4.2 tutorials.

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 19, 2013

Ask Questions?    Discuss: Hibernate Example Step by Step in Eclipse  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com