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
2
3
4
5
6
7
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)
);
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?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>
<?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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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;
    }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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>
<?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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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();
    }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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();
            }
        }
 
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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;
        }
}
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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);
 
    }
}
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

Karibasappa G C (KB)
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