Hibernate Tutorials : CRUD example in hibernate

CRUD example in Hibernate CRUD Example in hibernate

In this tutorial, I will discuss about the CRUD example in Hibernate framework. 

Before we begin, make sure your environment is ready for Hibernate framework. You can follow this Setting Up Environment for Hibernate tutorial in order to setup your environment and make simple Maven project.

If it is already done, please follow the directory structure as below :

CRUD example in Hibernate
CRUD example in Hibernate


Step 1 : Create Hibernate Configuration

Hibernate needs configuration parameters such as database settings, mappings files and connection pool settings. These information can be provided with the hibernate configuration file as configured below.
<?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/hibernatetestdb</property>
 <property name="connection.username">root</property>
 <property name="connection.password">admin</property>
 <property name="show_sql">true</property>

 <mapping class="com.hibernatetest.entities.User" />

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

Step 2 : Create Entity File

Below is the entity file.
package com.hibernatetest.entities;

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

@Entity
@Table(name = "USER")
public class User {

 @Id
 @Column(name = "id")
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 private int id;

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

 // Getter and Setters

}

Step 3 : Create Hibernate Util

We have create a hibernate util is a custom class which will provide SessionFactory object.
package com.hibernatetest.utils;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class SessionManagerUtil {

 private static final SessionFactory sessionFactory = buildSessionFactory();

 private static SessionFactory buildSessionFactory() {

 Configuration config = null;
 StandardServiceRegistryBuilder regBuilder = null;
 ServiceRegistry serviceReg = null;

 try {

 config = new Configuration();
 config.configure("hibernate.cfg.xml");

 regBuilder = new StandardServiceRegistryBuilder();
 regBuilder.applySettings(config.getProperties());

 serviceReg = regBuilder.build();

 return config.buildSessionFactory(serviceReg);

 } catch (Exception e) {
 throw new ExceptionInInitializerError(e.getMessage());
 }

 }

 public static SessionFactory getSessionFactory() {
 return sessionFactory;
 }
}

Step 4 : Create Main Class

Now create main class to create CRUD example in hibernate. Inside Main class, we have created different methods like addUser(), updateUser(), listUsers and deleteUser(). We will discuss different terms.
package com.hibernatetest.main;

import java.util.List;

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

import com.hibernatetest.entities.User;
import com.hibernatetest.utils.SessionManagerUtil;

public class Main {
 
 public static void main(String ...arg) {
 
 /*
 User user = new User();
 user.setName("Demo Name");
 
 addUser(user); */
 
 /*
 User user = new User();
 user.setId(2);
 user.setName("Demo Name Updated");
 
 updateUser(user); */
 
 /*
 listUsers(); */
 
 /*
 User user = new User();
 user.setId(2);
 
 deleteUser(user); */
 
 listUsers();
 
 }

 public static void addUser(User user) {

 SessionFactory factory = null;
 Session session = null;

 try {

 factory = SessionManagerUtil.getSessionFactory();
 session = factory.openSession();

 session.beginTransaction();
 session.save(user);

 session.getTransaction().commit();

 session.close();
 factory.close();

 } catch (Exception e) {

 session.getTransaction().rollback();

 session.close();
 factory.close();

 e.printStackTrace();
 }

 }
 
 public static void deleteUser(User user) {

 SessionFactory factory = null;
 Session session = null;

 try {

 factory = SessionManagerUtil.getSessionFactory();
 session = factory.openSession();

 session.beginTransaction();
 session.delete(user);

 session.getTransaction().commit();

 session.close();
 factory.close();

 } catch (Exception e) {

 session.getTransaction().rollback();

 session.close();
 factory.close();

 e.printStackTrace();
 }

 }

 public static void updateUser(User user) {

 SessionFactory factory = null;
 Session session = null;

 try {

 factory = SessionManagerUtil.getSessionFactory();
 session = factory.openSession();

 session.beginTransaction();
 session.saveOrUpdate(user);

 session.getTransaction().commit();

 session.close();
 factory.close();

 } catch (Exception e) {

 session.getTransaction().rollback();

 session.close();
 factory.close();

 e.printStackTrace();
 }

 }

public static void deleteUserWithLoad(int id) {

 SessionFactory factory = null;
 Session session = null;

 try {

 factory = SessionManagerUtil.getSessionFactory();
 session = factory.openSession();

 session.beginTransaction();
 
 User user = (User) session.load(User.class, id);
 session.delete(user);

 session.getTransaction().commit();

 session.close();
 factory.close();

 } catch (Exception e) {

 session.getTransaction().rollback();

 session.close();
 factory.close();

 e.printStackTrace();
 }

 }

 public static void listUsers() {

 SessionFactory factory = null;
 Session session = null;

 try {

 factory = SessionManagerUtil.getSessionFactory();
 session = factory.openSession();

 List<User> users = (List<User>) session.createQuery("from User").list();
 
 for (User user : users) {
 System.out.println("User name : " + user.getName());
 }

 session.close();
 factory.close();

 } catch (Exception e) {

 session.close();
 factory.close();

 e.printStackTrace();
 }

 }
}

Let’s discuss different methods of session object.

save(object) : Save method stores an object into the database. It will persist the given transient instance. It will first assign generated identifier. This method returns id of the entity created.

saveOrUpdate(object) : This method is same as save method but the difference is that if identifier exist then it will call update method otherwise it will simple call save method of session object.

load(Entity.class, identifer) : It returns the proxy object. Load method does not hit the database and if no row found throws the exception.

get(Entity.class, identifer) : It does not return any proxy object, means it will always hit the database and return the real object. If no row found, it does not throw any exception.

delete(object) : Delete the object from the database. An exception will be thrown if no record found in the database.

Related Post

4 thoughts on “Hibernate Tutorials : CRUD example in hibernate”

Leave a Reply

Your email address will not be published. Required fields are marked *