Skip to content
Related Articles
Open in App
Not now

Related Articles

CRUD Operations using Hibernate

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 31 Oct, 2022
Improve Article
Save Article

Hibernate is a Java framework that implements ORM(Object Relational Mapping) design pattern. It is used to map java objects into a relational database. It internally uses JDBC(Java Database Connectivity), JTA(Java Transaction API), and JNDI(Java Naming and Directory Interface). It helps to make java objects persist in the database without losing their state, thus, named Hibernate. It can be used to perform all the CRUD operations without having to write SQL queries. CRUD refers to database operations:

  • C -> Create/Insert
  • R -> Retrieve
  • U -> Update
  • D -> Delete

Given below are the examples that illustrate the use of Hibernate to perform CRUD operations. All the examples use MySQL for database management and ‘student_info’ as a sample database.

Example Project

SessionFactoryProvider.java:

It is used to create and return a SessionFactory object:

Java




import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
  
public class SessionFactoryProvider {
    public static SessionFactory provideSessionFactory()
    {
        Configuration config=new Configuration();
        config.configure();
        return config.buildSessionFactory();
    }
}


Student.java:

It is a POJO class that represents the object persistent in the database.

Java




import javax.persistence.*;
  
@Entity
public class Student {
    @Id
    private int id;
    private String name;
    private int std;
      
    public Student() {
    }
    public Student(int id, String name, int std) {
        this.id = id;
        this.name = name;
        this.std = std;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getStd() {
        return std;
    }
    public void setStd(int std) {
        this.std = std;
    }
}


hibernate.cfg.xml:

It is a configuration file used to provide database details, mapping resources, etc.. ‘hibernate.hbm2ddl.auto’ property in the configuration file is set to ‘create’ for creating tables in the database automatically. If the table already exists in the database ‘hibernate.hbm2ddl.auto’ is set to ‘update’. For creating tables automatically:

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student_info</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <mapping class="beans.Student"></mapping>
    </session-factory>
</hibernate-configuration>


For inserting, retrieving, updating, or deleting records from an existing table in the database:

hibernate.cfg.xml:

XML




<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.hbm2ddl.auto">update</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/student_info</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <mapping class="beans.Student"></mapping>
    </session-factory>
</hibernate-configuration>


Creating a table in the database and inserting a new record:

The following method of ‘org.hibernate.Session’ is used to persist the object in the database:

Serializable save(Object object)

Create.java:

Java




import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utilities.SessionFactoryProvider;
  
public class Create {
    public static void main(String[] args)
    {
        SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction t=session.beginTransaction();
          
        Student s=new Student(101,"John",10);
        session.save(s);
        t.commit();
          
        sessionFactory.close();
    }
}


The following details will be added to the database:

student table

 

Retrieving data from the database:

The following two methods are used to retrieve the data from the database:

<T> T  get(Class<T> entityType, Serializable id)

<T> T load(Class<T> theClass, Serializable id)

Difference between get() and load():

get()

load()

It returns null if the object doesn’t exist in the database or session cache. It throws ObjectNotFoundException if the object doesn’t exist in the database or session cache.
It returns fully initialized objects which may require multiple database classes. Therefore it affects the performance of the application. It returns a proxy object and initializes the object only if any method is called on the object(other than getId()). Therefore it results in better performance.
get() is used to fetch an object when it is not sure whether the object exists or not. load() is used to fetch an object if it is sure that object exists.

Retrieve.java:

Java




import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utilities.SessionFactoryProvider;
  
public class Retrieve {
    public static void main(String[] args)
    {
        SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory();
        Session session=sessionFactory.openSession();
          
        Student s=session.get(Student.class, 101);
        System.out.println("Id : "+s.getId());
        System.out.println("Name : "+s.getName());
        System.out.println("Class : "+s.getStd());
          
        sessionFactory.close();
    }
  
}


The following details will be fetched from the database:

Student record

 

If an object doesn’t exist in database, get() returns null whereas load() throws ObjectNotFoundexception.

Retrieve.java: 

Java




package crudOperations;
  
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import beans.Student;
import utilities.SessionFactoryProvider;
  
public class Retrieve {
    public static void main(String[] args)
    {
        SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory();
        Session session=sessionFactory.openSession();
          
        System.out.println("Fetching object using get:");
        Student s1=session.get(Student.class, 102);
        System.out.println(s1);
        System.out.println("Fetching object using load:");
        Student s2=session.load(Student.class,102);
        System.out.println(s2);
          
        sessionFactory.close();
    }
}


Output:

get() vs load()

 

Updating a record in the database:

Update.java:

Java




import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utilities.SessionFactoryProvider;
  
public class Update {
    public static void main(String[] args)
    {
        SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction t=session.beginTransaction();
          
        Student s=session.get(Student.class, 101);
        s.setStd(11);
        session.save(s);
        t.commit();
          
        sessionFactory.close();
    }
}


The following record will be updated:

Student table

 

Deleting a record from the database:

The following method of ‘org.hibernate.Session’ is used to delete an object:

void delete(Object object)

Delete.java:

Java




package crudOperations;
  
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
  
import beans.Student;
import utilities.SessionFactoryProvider;
  
public class Delete {
    public static void main(String[] args)
    {
        SessionFactory sessionFactory=SessionFactoryProvider.provideSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction t=session.beginTransaction();
          
        Student s=session.get(Student.class, 101);
        session.delete(s);
        t.commit();
          
        sessionFactory.close();
    }
}


Output:

Student table

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!