How to read and save data using Hibernate

How to read and save data using Hibernate?

Table of Contents

Hibernate is an ORM (Object-Relational Mapping) that is used to map the objects of Java classes with the relational database. It maps the java classes to database tables using XML configuration where you do not need to write any code.

How to read data?

Hibernate provides two different methods to read data from the database:

  1. get(): It returns a persistence object of a given class. It returns null when there is no persistence object available.
  2. load(): It also returns a persistence object of a given class but throws an exception (objectNotFoundException) if the entity is not available in the database.

Difference between get() and load()

Session.get()Session.load()
It never returns a proxy object.It always returns a proxy object.
It returns null when the entity is not available in the database and continues the execution.It throws an exception (objectNotFoundException) when the entity is not available in the database and terminates the execution.
Eager Loading; It hits the database immediately and returns the object.Lazy Loading; It hits the database only when it tries to retrieve the object.
They are used for the SELECT operation.They are used for DELETE and UPDATE operations.


Let us now understand the Session.get() using an example.

1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>HibernateGet</groupId>
    <artifactId>HibernateGet</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <!-- Hibernate 4.3.6 Final -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.6.Final</version>
        </dependency>
        <!-- Mysql Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>${project.artifactId}</finalName>
    </build>
</project>

2) Create a database table

CREATE DATABASE IF NOT EXISTS tutorialDb;
 
USE tutorialDb;
 
DROP TABLE IF EXISTS employee;
 
CREATE TABLE employee (
    emp_id INT(50) NOT NULL AUTO_INCREMENT, 
    emp_fname VARCHAR(200) DEFAULT NULL, 
    emp_lname VARCHAR(200) DEFAULT NULL,
    emp_age INT(50) DEFAULT NULL,
    emp_education VARCHAR(200) DEFAULT NULL, 
    emp_salary INT(100) DEFAULT NULL, 
    PRIMARY KEY (emp_id)
);

3) Create Employee.java

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="employee")
public class Employee {
 
    @Id
    @Column(name = "emp_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int employeeId;
 
    @Column(name = "emp_fname")
    private String firstName;
 
    @Column(name = "emp_lname")
    private String lastName;
 
    @Column(name = "emp_age")
    private int age;
 
    @Column(name = "emp_education")
    private String education;
 
    @Column(name = "emp_salary")
    private int salary;
 
    public int getEmployeeId() {
        return employeeId;
    }
 
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
 
    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 int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public String getEducation() {
        return education;
    }
 
    public void setEducation(String education) {
        this.education = education;
    }
 
    public int getSalary() {
        return salary;
    }
 
    public void setSalary(int salary) {
        this.salary = salary;
    }
 
    public String toString() {
        return "Id: " + employeeId + ", Name: " + firstName + " " + lastName + ", Age: " + age + ", Education: " + education + ", Salary:" + salary + "$\n";
    }
}

4) HibernateUtil.java

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
 
public class HibernateUtil {
 
    static Session sessionObj;
    static SessionFactory sessionFactoryObj;
 
     private static SessionFactory buildSessionFactory() {
        Configuration configObj = new Configuration();
        configObj.configure("hibernate.cfg.xml");
       ServiceRegistry serviceRegistryObj = new               StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build(); 
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
        return sessionFactoryObj;
    }
 
public static void createRecord() {     
        Employee empObj;
        int empAge = 26, empSal = 1000;
        try {
            sessionObj = buildSessionFactory().openSession();
            sessionObj.beginTransaction();
 
            for(int j=101; j <= 105; j++) {
                empObj = new Employee();
                empObj.setFirstName("Editor");
                empObj.setLastName(String.valueOf(j));
                empObj.setAge(empAge);
                empObj.setEducation("Post Graduation");
                empObj.setSalary(empSal);
 
                empAge = empAge + 3;
                empSal = empSal + 500;
 
                sessionObj.save(empObj);
            }
 
            System.out.println("\n.......Records Saved Successfully In The Database.......\n");
 
           sessionObj.getTransaction().commit();
        } catch(Exception sqlException) {
            if(null != sessionObj.getTransaction()) {
                System.out.println("\n.......Transaction Is Being Rolled Back.......");
                sessionObj.getTransaction().rollback();
            }
            sqlException.printStackTrace();
        } finally {
            if(sessionObj != null) {
                sessionObj.close();
            }
        }
    }
 
    public static void displayRecords() {
        int emp_id;
        Employee empObj;
        try {
            sessionObj = buildSessionFactory().openSession();
 
            emp_id=1;
            empObj = (Employee)sessionObj.get(Employee.class, new Integer(emp_id));
            if(empObj != null) {
                System.out.println("\nEmployee Record?= " + empObj.toString());
            }
 
            emp_id = 6;
            empObj = (Employee)sessionObj.get(Employee.class, new Integer(emp_id));
            if(empObj != null) {
                System.out.println("\nEmployee Record?= " + empObj.toString());
            } else {
                System.out.println(empObj);
            }
        } catch(Exception sqlException) {
            if(null != sessionObj.getTransaction()) {
                System.out.println("\n.......Transaction Is Being Rolled Back.......");
                sessionObj.getTransaction().rollback();
            }
            sqlException.printStackTrace();
        } finally {
            if(sessionObj != null) {
                sessionObj.close();
            }
        }
    }
}

5) Implement Main Class – AppMain.java

package com.jcg.hibernate.get;
 
public class AppMain {
 
    public static void main(String[] args) {
        System.out.println(".......Hibernate Get Example.......\n");
 
        HibernateUtil.createRecord();
 
        HibernateUtil.displayRecords();
 
        System.exit(0);
    }
}

6) Hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
 
<hibernate-configuration>
    <session-factory>
        <!-- SQL Dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Database Connection Settings -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/tutorialDb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password"></property>
 
        <!-- Echo All Executed SQL To Console -->
        <property name="show_sql">true</property>
 
        <!-- Specifying Session Context -->
        <property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
 
        <!-- Mapping With Model Class Containing Annotations -->
        <mapping class="com.jcg.hibernate.get.Employee" />
    </session-factory>
</hibernate-configuration>

How to Save Data?

Hibernate provides different methods to save data into the database:

  1. save(): It returns a generated identifier and throws an exception when an entity is already available in the database.
  2. persist (): It returns a void and throws an exception when an entity is already available in the database.
  3. saveOrUpdate(): It is used to either save or update the entity in the database.

Let us now understand these using some examples.

1) pom.xml

<dependencies>
    <!-- Mysql Connector -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6.0.5</version>
    </dependency>
    <!-- Hibernate 5.2.6 Final -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.6.Final</version>
    </dependency>
  </dependencies>

2) Customer.java

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

@Entity
@Table(name = "CUSTOMER_TBL")
public class Customer {
  @Id
  @Column(name = "CUST_ID")
  private Long id;

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

  public Long getId() {
    return id;
  }

  public void setId(Long id) {
    this.id = id;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

3) HibernateUtil.java

import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        StandardServiceRegistryBuilder registryBuilder = 
            new StandardServiceRegistryBuilder();

        Map<String, String> settings = new HashMap<>();
        settings.put("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
        settings.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/SONALI");
        settings.put("hibernate.connection.username", "root");
        settings.put("hibernate.connection.password", "admin");
        settings.put("hibernate.show_sql", "true");
        settings.put("hibernate.hbm2ddl.auto", "update");

        registryBuilder.applySettings(settings);

        registry = registryBuilder.build();

        MetadataSources sources = new MetadataSources(registry)
            .addAnnotatedClass(Customer.class);

        Metadata metadata = sources.getMetadataBuilder().build();

        sessionFactory = metadata.getSessionFactoryBuilder().build();
      } catch (Exception e) {
        System.out.println("SessionFactory creation failed");
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }
    return sessionFactory;
  }

  public static void shutdown() {
    if (registry != null) {
      StandardServiceRegistryBuilder.destroy(registry);
    }
  }
}

4) SessionSaveExample.java using save() method

import org.hibernate.Session;
import org.hibernate.Transaction;

public class SessionSaveExample {
  public static void main(String[] args) {
    Session session = null;
    Transaction transaction = null;
    try {
      session = HibernateUtil.getSessionFactory().openSession();
      transaction = session.beginTransaction();
      transaction.begin();

      Customer customer = new Customer();
      customer.setId(1l);
      customer.setName("Sunil");
      session.save(customer);

      transaction.commit();
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null) {
        session.close();
      }
    }

    HibernateUtil.shutdown();
  }
}

5) SessionPersistExample.java using persist() method

import org.hibernate.Session;
import org.hibernate.Transaction;

public class SessionPersistExample {
  public static void main(String[] args) {
    Session session = null;
    Transaction transaction = null;
    try {
      session = HibernateUtil.getSessionFactory().openSession();
      transaction = session.beginTransaction();
      transaction.begin();

      Customer customer = new Customer();
      customer.setId(2l);
      customer.setName("Joe");
      session.persist(customer);

      transaction.commit();
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null) {
        session.close();
      }
    }

    HibernateUtil.shutdown();
  }
}

6) SessionSaveOrUpdateExample.java using saveOrUpdate() method

import org.hibernate.Session;
import org.hibernate.Transaction;

public class SessionSaveOrUpdateExample {
  public static void main(String[] args) {
    Session session = null;
    Transaction transaction = null;
    try {
      session = HibernateUtil.getSessionFactory().openSession();
      transaction = session.beginTransaction();
      transaction.begin();

      Customer customer = new Customer();
      customer.setId(3l);
      customer.setName("Mike");
      session.saveOrUpdate(customer);

      transaction.commit();
    } catch (Exception e) {
      if (transaction != null) {
        transaction.rollback();
      }
      e.printStackTrace();
    } finally {
      if (session != null) {
        session.close();
      }
    }
    HibernateUtil.shutdown();
  }
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share this article
Subscribe
By pressing the Subscribe button, you confirm that you have read our Privacy Policy.
Need a Free Demo Class?
Join H2K Infosys IT Online Training
Enroll Free demo class