Hibernate Example Project with Annotation using Eclipse IDE

In this tutorial, we are going to create a simple example of Hibernate Application using Eclipse IDE
For this example application we'll follow following steps:

Step 1: Create a Java Project using Eclipse IDE

Open Eclipse IDE
Click on File -> New -> Project -> Java Project
Specify the Project Name as HibernateSampleProject then
click on Next -> Finish

Create the following packages

com.blogspot.sonevalley.main
com.blogspot.sonevalley.model
com.blogspot.sonevalley.util

Step 2: Download & Add Hibernate jar Files

Download Hibernate jar files

To download Hibernate jar files click on the below link to open download page of Hibernate official website

Download Hibernate jar Files
Download Hibernate jar Files

Download the stable version of Hibernate and extract the files

Add Hibernate jar Files to Project

Right click on Project (HibernateSampleProject) in Package Explore
Click on Build Path -> Add External Archives...
Add Hibernate jar Files to Hibernate Sample Project
Add Hibernate jar Files to Hibernate Sample Project

Locate the extracted directory of downloaded Hibernate ORM Downloads
Go to lib -> required 
Select all the jar files and click on open

Step 3: Download & Add MySQL connector jar File

Download MySQL connector jar file

To download Connector/J file, click on the below link to open download page of MySQL official website.

Add MySQL connector jar file

To add MySQL Connector/J file, follow similar step as we follow for adding Hibernate jar files

Step 4: Create a Hibernate Configuration file

Create a file hibernate.cfg.xml and add the below code
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/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:3306/my_db</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <!-- JDBC connection pool (use the built-in) -->
        <!-- <property name="connection.pool_size">1</property> -->

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
        
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        
        <!-- Drop the existing table and create new one -->
        <property name="hbm2ddl.auto">create</property>
  
        <!-- Mention here all the model classes -->
        <mapping class="com.blogspot.sonevalley.model.CustomerEntity"/>
        <mapping class="com.blogspot.sonevalley.model.OrderEntity"/>

    </session-factory>

</hibernate-configuration>

<property name="hbm2ddl.auto">create</property>
The above property will create the table automatically and if already exist It'll drop table and create a new one each time you run the application. If you want to avoid recreating the table then replace create with update.

<property name="connection.pool_size">1</property>
connection.pool_size indicates the maximum number of pooled connection. If you don't want to define just remove this property.

Step 5: Add the Following Files to Project

Create Hibernate Model Class in com.blogspot.sonevalley.model package
CustomerEntity.java
package com.blogspot.sonevalley.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Customer")
public class CustomerEntity {
 
 @Id
 @GeneratedValue
 private long customerId;
 private String customerName;
 
 public CustomerEntity(String customerName) {
  super();
  this.customerName = customerName;
 }
 public long getCustomerId() {
  return customerId;
 }
 public void setCustomerId(long customerId) {
  this.customerId = customerId;
 }
 public String getCustomerName() {
  return customerName;
 }
 public void setCustomerName(String customerName) {
  this.customerName = customerName;
 }

}

Add HibernateUtil.java file to com.blogspot.sonevalley.util package
HibernateUtil.java
package com.blogspot.sonevalley.util;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 
 private static SessionFactory sessionFactory;
 private static SessionFactory buildSessionFactory() {
  try {
   // Creating the SessionFactory from hibernate.cfg.xml
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   return sessionFactory;
   
  } catch(Throwable ex) {
   ex.printStackTrace();
   throw new ExceptionInInitializerError(ex);
  }
 }
 
 public static SessionFactory getSessionFactory() {
  if(sessionFactory == null) {
   sessionFactory = buildSessionFactory();
  }
  return sessionFactory;
 }
}

Add Main.java file to com.blogspot.sonevalley.main package
Main.java
package com.blogspot.sonevalley.main;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.blogspot.sonevalley.model.CustomerEntity;
import com.blogspot.sonevalley.util.HibernateUtil;

public class Main {
 
 public static void main(String[] args) {
  
  Transaction transaction = null;
  SessionFactory sessionFactory = null;
  CustomerEntity customer1 = new CustomerEntity("Sushil Kumar");
  CustomerEntity customer2 = new CustomerEntity("Vijay Pandey");
  
  try {
   sessionFactory = HibernateUtil.getSessionFactory();
   Session session = sessionFactory.getCurrentSession();
   transaction = session.beginTransaction();
   session.save(customer1);
   session.save(customer2);
   transaction.commit();
   System.out.println("Customer Record Saved!");
  } catch(HibernateException e) {
   transaction.rollback();
   e.printStackTrace();
  } finally {
   sessionFactory.close();
  }
 }
}


Directory Structure (Package Explorer)

Directory Structure of Hibernate Sample Application
Directory Structure in Package Explorer

Run the Project

Right Click on the Project
Click on Run as -> Java Application
customer table will look like this once you run the project
Hibernate Sample Application Table
customer table

Click on the below button to download this project

Download Project



SHARE
    Blogger Comment
    Facebook Comment

3 comments:

  1. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Hibernate Training in Electronic City

    ReplyDelete
  2. Happy to found this blog. Good Post!. It was so good to read and useful to improve my knowledge as updated one, keep blogging. Hibernate Training in Electronic City
    Java Training in Electronic City

    ReplyDelete
  3. As reported by Stanford Medical, It's really the one and ONLY reason women in this country get to live 10 years longer and weigh an average of 42 lbs lighter than we do.

    (Just so you know, it really has NOTHING to do with genetics or some secret exercise and absolutely EVERYTHING to related to "how" they are eating.)

    P.S, What I said is "HOW", and not "what"...

    Click on this link to determine if this short quiz can help you release your real weight loss potential

    ReplyDelete