Hibernate CRUD operations with Java Web application

Let’s see the CRUD operations in Hibernate with Java and MYSQL


Tools and Technologies used

Java

Eclipse

Maven

Hibernate

MySql database


Step 1

First create the database schema and tables to perform the CRUD operations

Copy and run the below scripts in the MySQL command window or MySQL workbench(GUI Tool) –> SQL Editor

I am using Command window to run these scripts
Go to MySql bin directory under MySql installation path E:\MySql_Install\bin

Issue the following command

mysql –u root –p

Enter the password

mysql_command_line2

Now run these scripts

  1. create database javainsimpleway;
create database javainsimpleway;

  1. use javainsimpleway;
use javainsimpleway;

  1. CREATE TABLE users (
  2.   Id int(15) NOT NULL AUTO_INCREMENT,
  3.   FirstName varchar(50),
  4.   LastName varchar(50),
  5.   Dob date,
  6.   Email varchar(100),
  7.   PRIMARY KEY (Id)
  8. );
CREATE TABLE users (
  Id int(15) NOT NULL AUTO_INCREMENT,
  FirstName varchar(50),
  LastName varchar(50),
  Dob date,
  Email varchar(100),
  PRIMARY KEY (Id)
);


Check the table created using below command

  1. desc users;
desc users;


mysql_create_users_table3

Step 2

Create a Java Maven web project in eclipse and setup Hibernate

Please refer this article on how to do it.

Step 3

Create the hibernate configuration file

hibernate.cfg.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-configuration PUBLIC
  3.        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  4.        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
  5.  
  6. <hibernate-configuration>
  7.  
  8.    <session-factory>
  9.  
  10.        <!-- Database connection properties -->
  11.        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
  12.        <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
  13.        <property name="connection.username">root</property>
  14.        <property name="connection.password">root</property>
  15.  
  16.        <!-- JDBC connection pool (using the built-in) -->
  17.        <property name="connection.pool_size">1</property>
  18.  
  19.        <!-- SQL dialect -->
  20.        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  21.  
  22.        <!-- Disable the second-level cache -->
  23.        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
  24.  
  25.        <!-- Echo all executed SQL to stdout -->
  26.        <property name="show_sql">true</property>
  27.        
  28.        <!-- Format the generated Sql -->
  29.        <property name="format_sql">true</property>
  30.  
  31.        <!-- Dont Drop and re-create the database schema on startup,Just update it -->
  32.        <property name="hbm2ddl.auto">update</property>
  33.  
  34.        <mapping resource="com/kb/mapping/user.hbm.xml"/>
  35.  
  36.    </session-factory>
  37.  
  38. </hibernate-configuration>
<?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 properties -->
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
       <property name="connection.url">jdbc:mysql://localhost/javainsimpleway</property>
       <property name="connection.username">root</property>
       <property name="connection.password">root</property>
 
       <!-- JDBC connection pool (using the built-in) -->
       <property name="connection.pool_size">1</property>
 
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
       <!-- Disable the second-level cache -->
       <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
       
       <!-- Format the generated Sql -->
       <property name="format_sql">true</property>
 
       <!-- Dont Drop and re-create the database schema on startup,Just update it -->
       <property name="hbm2ddl.auto">update</property>
 
       <mapping resource="com/kb/mapping/user.hbm.xml"/>
 
   </session-factory>
 
</hibernate-configuration>


We have added database settings and mapping resource in the above configuration file.

Step 4

Create a User model class under src/main/java/com/kb/model package

  1. package com.kb.model;
  2.  
  3. import java.util.Date;
  4.  
  5. public class User {
  6.     private int id;
  7.     private String firstName;
  8.     private String lastName;
  9.     private Date dob;
  10.     private String email;
  11.     public int getId() {
  12.         return id;
  13.     }
  14.     public void setId(int id) {
  15.         this.id = id;
  16.     }
  17.     public String getFirstName() {
  18.         return firstName;
  19.     }
  20.     public void setFirstName(String firstName) {
  21.         this.firstName = firstName;
  22.     }
  23.     public String getLastName() {
  24.         return lastName;
  25.     }
  26.     public void setLastName(String lastName) {
  27.         this.lastName = lastName;
  28.     }
  29.     public Date getDob() {
  30.         return dob;
  31.     }
  32.     public void setDob(Date dob) {
  33.         this.dob = dob;
  34.     }
  35.     public String getEmail() {
  36.         return email;
  37.     }
  38.     public void setEmail(String email) {
  39.         this.email = email;
  40.     }
  41. }
package com.kb.model;

import java.util.Date;

public class User {
	private int id;
    private String firstName;
    private String lastName;
    private Date dob;
    private String email;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getFirstName() {
		return firstName;
	}
	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}
	public String getLastName() {
		return lastName;
	}
	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
	public Date getDob() {
		return dob;
	}
	public void setDob(Date dob) {
		this.dob = dob;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}

Step 5

Create the mapping file for User Model under src/main/resources/com/kb/mapping folder(create this folder if not exist)

user.hbm.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE hibernate-mapping PUBLIC
  3. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  4. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  5.  
  6. <hibernate-mapping>
  7.     <class name="com.kb.model.User" table="users">
  8.         <id name="id" type="int" column="Id">
  9.             <generator class="increment" />
  10.         </id>
  11.         <property name="firstName">
  12.             <column name="FirstName" />
  13.         </property>
  14.         <property name="lastName">
  15.             <column name="LastName" />
  16.         </property>
  17.         <property name="dob">
  18.             <column name="Dob" />
  19.         </property>
  20.         <property name="email">
  21.             <column name="Email" />
  22.         </property>
  23.     </class>
  24. </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.kb.model.User" table="users">
        <id name="id" type="int" column="Id">
            <generator class="increment" />
        </id>
        <property name="firstName">
            <column name="FirstName" />
        </property>
        <property name="lastName">
            <column name="LastName" />
        </property>
        <property name="dob">
            <column name="Dob" />
        </property>
        <property name="email">
            <column name="Email" />
        </property>
    </class>
</hibernate-mapping>


In the above mapping file, we have mapped UserModel to users table and each property of UserModel class to columns in the database

Step 6

Create a new Utility class called HibernateUtil.java under src/main/java/com/kb/util package

  1. package com.kb.util;
  2.  
  3. import org.hibernate.SessionFactory;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. public class HibernateUtil {
  7.     private static final SessionFactory sessionFactory = buildSessionFactory();
  8.  
  9.     private static SessionFactory buildSessionFactory() {
  10.         try {
  11.             // Create the SessionFactory from hibernate.cfg.xml
  12.             return new Configuration().configure().buildSessionFactory();
  13.         } catch (Throwable ex) {
  14.             // Make sure you log the exception to track it
  15.             System.err.println("SessionFactory creation failed." + ex);
  16.             throw new ExceptionInInitializerError(ex);
  17.         }
  18.     }
  19.  
  20.     public static SessionFactory getSessionFactory() {
  21.         return sessionFactory;
  22.     }
  23.    
  24.     public static void shutdown() {
  25.         // Optional but can be used to Close caches and connection pools
  26.         getSessionFactory().close();
  27.     }
  28.  
  29. }
package com.kb.util;

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

public class HibernateUtil {
	private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception to track it
            System.err.println("SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static void shutdown() {
    	// Optional but can be used to Close caches and connection pools
    	getSessionFactory().close();
    }

}


In this class, we are loading the hibernate configuration file and building the SessionFactory and this code can be reused whenever we need to get the SessionFactory object.

Step 7

Create DAO class to interact with Database under src/main/java/com/kb/dao package

UserDao.java

  1. package com.kb.dao;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.List;
  5.  
  6. import org.hibernate.Session;
  7. import org.hibernate.Transaction;
  8. import org.hibernate.query.Query;
  9.  
  10. import com.kb.model.User;
  11. import com.kb.util.HibernateUtil;
  12.  
  13. public class UserDao {
  14.    
  15.     //Create of CRUD
  16.      public void addUser(User user) {
  17.             Transaction trns = null;
  18.             Session session = HibernateUtil.getSessionFactory().openSession();
  19.             try {
  20.                 trns = session.beginTransaction();
  21.                 session.save(user);
  22.                 session.getTransaction().commit();
  23.             } catch (RuntimeException e) {
  24.                 if (trns != null) {
  25.                     trns.rollback();
  26.                 }
  27.                 e.printStackTrace();
  28.             } finally {
  29.                 session.flush();
  30.                 session.close();
  31.             }
  32.         }
  33.      
  34.      //Read of CRUD
  35.     @SuppressWarnings("unchecked")
  36.     public List<User> getAllUsers() {
  37.             List<User> users = new ArrayList<User>();
  38.             Session session = HibernateUtil.getSessionFactory().openSession();
  39.             try {
  40.                 users = session.createQuery("from User").getResultList();
  41.             } catch (RuntimeException e) {
  42.                 e.printStackTrace();
  43.             } finally {
  44.                 session.flush();
  45.                 session.close();
  46.             }
  47.             return users;
  48.         }
  49.  
  50.     //Read of CRUD
  51.         public User getUserById(int userid) {
  52.             User user = null;
  53.             Session session = HibernateUtil.getSessionFactory().openSession();
  54.             try {
  55.                 String hqlQuery = "from User where id = :id";
  56.                 @SuppressWarnings("rawtypes")
  57.                 Query query = session.createQuery(hqlQuery);
  58.                 query.setParameter("id", userid);
  59.                 user = (User) query.getSingleResult();
  60.             } catch (RuntimeException e) {
  61.                 e.printStackTrace();
  62.             } finally {
  63.                 session.flush();
  64.                 session.close();
  65.             }
  66.             return user;
  67.         }
  68.        
  69.       //Update of CRUD
  70.         public void updateUser(User user) {
  71.             Transaction trns = null;
  72.             Session session = HibernateUtil.getSessionFactory().openSession();
  73.             try {
  74.                 trns = session.beginTransaction();
  75.                 session.update(user);
  76.                 session.getTransaction().commit();
  77.             } catch (RuntimeException e) {
  78.                 if (trns != null) {
  79.                     trns.rollback();
  80.                 }
  81.                 e.printStackTrace();
  82.             } finally {
  83.                 session.flush();
  84.                 session.close();
  85.             }
  86.         }
  87.  
  88.         //Delete of CRUD
  89.         public void deleteUser(int userid) {
  90.             Transaction trns = null;
  91.             Session session = HibernateUtil.getSessionFactory().openSession();
  92.             try {
  93.                 trns = session.beginTransaction();
  94.                 User user = (User) session.load(User.class, new Integer(userid));
  95.                 session.delete(user);
  96.                 session.getTransaction().commit();
  97.             } catch (RuntimeException e) {
  98.                 if (trns != null) {
  99.                     trns.rollback();
  100.                 }
  101.                 e.printStackTrace();
  102.             } finally {
  103.                 session.flush();
  104.                 session.close();
  105.             }
  106.         }
  107.  
  108. }
package com.kb.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.kb.model.User;
import com.kb.util.HibernateUtil;

public class UserDao {
	
	//Create of CRUD
	 public void addUser(User user) {
	        Transaction trns = null;
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        try {
	            trns = session.beginTransaction();
	            session.save(user);
	            session.getTransaction().commit();
	        } catch (RuntimeException e) {
	            if (trns != null) {
	                trns.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.flush();
	            session.close();
	        }
	    }
	 
	 //Read of CRUD
	@SuppressWarnings("unchecked")
	public List<User> getAllUsers() {
	        List<User> users = new ArrayList<User>();
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        try {
	            users = session.createQuery("from User").getResultList();
	        } catch (RuntimeException e) {
	            e.printStackTrace();
	        } finally {
	            session.flush();
	            session.close();
	        }
	        return users;
	    }

	//Read of CRUD
	    public User getUserById(int userid) {
	        User user = null;
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        try {
	            String hqlQuery = "from User where id = :id";
	            @SuppressWarnings("rawtypes")
				Query query = session.createQuery(hqlQuery);
	            query.setParameter("id", userid);
	            user = (User) query.getSingleResult();
	        } catch (RuntimeException e) {
	            e.printStackTrace();
	        } finally {
	            session.flush();
	            session.close();
	        }
	        return user;
	    }
	    
	  //Update of CRUD
	    public void updateUser(User user) {
	        Transaction trns = null;
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        try {
	            trns = session.beginTransaction();
	            session.update(user);
	            session.getTransaction().commit();
	        } catch (RuntimeException e) {
	            if (trns != null) {
	                trns.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.flush();
	            session.close();
	        }
	    }

	    //Delete of CRUD
	    public void deleteUser(int userid) {
	        Transaction trns = null;
	        Session session = HibernateUtil.getSessionFactory().openSession();
	        try {
	            trns = session.beginTransaction();
	            User user = (User) session.load(User.class, new Integer(userid));
	            session.delete(user);
	            session.getTransaction().commit();
	        } catch (RuntimeException e) {
	            if (trns != null) {
	                trns.rollback();
	            }
	            e.printStackTrace();
	        } finally {
	            session.flush();
	            session.close();
	        }
	    }
 
}


In the above class,we have created method for each CRUD operation and performing appropriate operation in it.

Step 8

Create Service class to interact with DAO layer under src/main/java/com/kb/service package

UserService.java

  1. package com.kb.service;
  2.  
  3. import java.util.List;
  4.  
  5. import com.kb.dao.UserDao;
  6. import com.kb.model.User;
  7.  
  8. public class UserService {
  9.  
  10.     private UserDao userDao;
  11.    
  12.     //Create of CRUD
  13.      public void addUser(User user) {
  14.          userDao.addUser(user);
  15.          }
  16.      
  17.      //Read of CRUD
  18.     public List<User> getAllUsers() {
  19.         return userDao.getAllUsers();
  20.     }
  21.  
  22.     //Read of CRUD
  23.         public User getUserById(int userid) {
  24.             return userDao.getUserById(userid);
  25.         }
  26.        
  27.       //Update of CRUD
  28.         public void updateUser(User user) {
  29.             userDao.updateUser(user);
  30.         }
  31.  
  32.         //Delete of CRUD
  33.         public void deleteUser(int userid) {
  34.             userDao.deleteUser(userid);
  35.         }
  36.  
  37.         public UserDao getUserDao() {
  38.             return userDao;
  39.         }
  40.  
  41.         public void setUserDao(UserDao userDao) {
  42.             this.userDao = userDao;
  43.         }
  44. }
package com.kb.service;

import java.util.List;

import com.kb.dao.UserDao;
import com.kb.model.User;

public class UserService {

	private UserDao userDao;
	
	//Create of CRUD
	 public void addUser(User user) {
		 userDao.addUser(user);
		 }
	 
	 //Read of CRUD
	public List<User> getAllUsers() {
		return userDao.getAllUsers();
	}

	//Read of CRUD
	    public User getUserById(int userid) {
	    	return userDao.getUserById(userid);
	    }
	    
	  //Update of CRUD
	    public void updateUser(User user) {
	    	userDao.updateUser(user);
	    }

	    //Delete of CRUD
	    public void deleteUser(int userid) {
	    	userDao.deleteUser(userid);
	    }

		public UserDao getUserDao() {
			return userDao;
		}

		public void setUserDao(UserDao userDao) {
			this.userDao = userDao;
		}
}

Step 9

Create Main client class to perform CRUD operations under src/main/java/com/kb/client package

UserClient.java

  1. package com.kb.client;
  2.  
  3. import java.text.ParseException;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6.  
  7. import com.kb.dao.UserDao;
  8. import com.kb.model.User;
  9. import com.kb.service.UserService;
  10.  
  11. public class UserClient {
  12.     public static void main(String[] args) {
  13.         UserService userService = new UserService();
  14.         UserDao userDao = new UserDao();
  15.         userService.setUserDao(userDao);
  16.  
  17.         // Add new user - Create of CRUD
  18.         User user1 = new User();
  19.         user1.setFirstName("John");
  20.         user1.setLastName("JC");
  21.         try {
  22.             Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1995-01-01");
  23.             user1.setDob(dob);
  24.         } catch (ParseException e) {
  25.             e.printStackTrace();
  26.         }
  27.         user1.setEmail("john@sample.com");
  28.         User user2 = new User();
  29.         user2.setFirstName("Robin");
  30.         user2.setLastName("RC");
  31.         try {
  32.             Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1975-01-01");
  33.             user2.setDob(dob);
  34.         } catch (ParseException e) {
  35.             e.printStackTrace();
  36.         }
  37.         user2.setEmail("robin@sample.com");
  38.        
  39.         userService.addUser(user1);
  40.         userService.addUser(user2);
  41.  
  42.         // Get all users - Read of CRUD
  43.         for (User retrivedUser : userService.getAllUsers()) {
  44.             System.out.println(retrivedUser.getFirstName());
  45.             System.out.println(retrivedUser.getLastName());
  46.             System.out.println(retrivedUser.getEmail());
  47.             System.out.println(retrivedUser.getDob());
  48.         }
  49.        
  50.         // Get user by id - Read of CRUD
  51.         User retrivedUser = userService.getUserById(1);
  52.         System.out.println(retrivedUser.getFirstName());
  53.         System.out.println(retrivedUser.getLastName());
  54.         System.out.println(retrivedUser.getEmail());
  55.         System.out.println(retrivedUser.getDob());
  56.  
  57.         // Update user - Update of CRUD
  58.         user1.setEmail("johnUpdated@sample.com");
  59.         user1.setId(1);
  60.         userService.updateUser(user1);
  61.  
  62.         // Delete user - Delete of CRUD
  63.         userService.deleteUser(1);
  64.  
  65.     }
  66. }
package com.kb.client;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.kb.dao.UserDao;
import com.kb.model.User;
import com.kb.service.UserService;

public class UserClient {
	public static void main(String[] args) {
		UserService userService = new UserService();
		UserDao userDao = new UserDao();
		userService.setUserDao(userDao);

		// Add new user - Create of CRUD
		User user1 = new User();
		user1.setFirstName("John");
		user1.setLastName("JC");
		try {
			Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1995-01-01");
			user1.setDob(dob);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		user1.setEmail("john@sample.com");
		User user2 = new User();
		user2.setFirstName("Robin");
		user2.setLastName("RC");
		try {
			Date dob = new SimpleDateFormat("yyyy-MM-dd").parse("1975-01-01");
			user2.setDob(dob);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		user2.setEmail("robin@sample.com");
		
		userService.addUser(user1);
		userService.addUser(user2);

		// Get all users - Read of CRUD
		for (User retrivedUser : userService.getAllUsers()) {
			System.out.println(retrivedUser.getFirstName());
			System.out.println(retrivedUser.getLastName());
			System.out.println(retrivedUser.getEmail());
			System.out.println(retrivedUser.getDob());
		}
		
		// Get user by id - Read of CRUD
		User retrivedUser = userService.getUserById(1);
		System.out.println(retrivedUser.getFirstName());
		System.out.println(retrivedUser.getLastName());
		System.out.println(retrivedUser.getEmail());
		System.out.println(retrivedUser.getDob());

		// Update user - Update of CRUD
		user1.setEmail("johnUpdated@sample.com");
		user1.setId(1);
		userService.updateUser(user1);

		// Delete user - Delete of CRUD
		userService.deleteUser(1);

	}
}


Run the above class and observer the queries in the console

CRUD_Java_output_queries_1
CRUD_Java_output_queries_2

Go to MySql console and check the output

CRUD_Java_output_table_1

We can see only one Record with Id “2” in the table as other record with id ”1” got inserted and deleted.

Download this project HibernateCRUDJava.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on