How to read and save data using Hibernate?

How to read and save data using Hibernate?
Techiio-author
Written by Sagar RabidasFebruary 21, 2022
34 min read
Hibernate
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

How to read and save data using Hibernate? Today we will discuss in this topic.

Introduction of Hibernate:-

Hibernate is an ORM (Object-Relational Mapping) that is used to map the gadgets of java instructions with the relational database. It maps the java training to database tables using XML configuration where you do no longer need to put in writing 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.

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

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>

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)
);

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";
    }
}

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();
            }
        }
    }
}

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);
    }
}

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.

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>

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;
  }
}

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);
    }
  }
}

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();
  }
}

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();
  }
}

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();
  }
}

Hibernate
Java
read and save data
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance