Hibernate CRUD operations with Java Web application
Let’s see the CRUD operations in Hibernate with Java and MYSQL
Tools and Technologies used
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
Now run these scripts
- create database javainsimpleway;
create database javainsimpleway;
- use javainsimpleway;
use javainsimpleway;
- 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
- desc users;
desc users;
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
- <?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
- 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
- <?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
- 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
- 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
- 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
- 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
Go to MySql console and check the output
We can see only one Record with Id “2” in the table as other record with id ”1” got inserted and deleted.
It is one of the simplest but effective tutorial , appreciate your efforts but one small correction HibernateUtil class should be declare as static. one more suggestion please increase font size and make it bold so it would be nice to read it.
HibernateUtil class not required to be static, only methods inside it are required to be static so that we can call those methods using class name.
Sure will check other things.
Thanks for appreciating and provide feedback !!
First of all, it’s a nice tutorial with nice efforts.
One small correction in “connection.url” property
Please update as below, if i’m not wrong.
jdbc:mysql://localhost:3306/javainsimpleway
Hi,
If we don’t specify port, then by default it takes 3306 only.
It’s optional but can be specified.
Thank you !!