Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Hibernate-Saving to Database

Now, we will see how hibernate saves data to the database.

As we have seen above,

i.e. Say there is a java class Employee :


class Employee{
   int id;
   String name;
   ---Getters & Setters---
}


Similarly in the database there is a table EMPLOYEE :

CREATE TABLE EMPLOYEE (ID INTEGER, NAME VARCHAR);

So, what we are going to do is initialize some values to Employee object and with the help of Hibernate, we are going to push it to the EMPLOYEE table.


Below is the code:


import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSave {
   public static void main(String[] args) {

    static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();

    Employee employee = new Employee();
    employee.setId(1);
    employee.setName("Joe");
    session.save(employee);

    session.getTransaction().commit();
    session.close();
    sessionFactory.close();
   }
}

1. In the first step we need to get the 'SessionFactory'. And, as we know the details of 'SessionFactory' is in the configuration file 'hibernate.cfg.xml'. So, we are using 'new Configuration().configure().buildSessionFactory()' to build the 'SessionFactory' first.

static SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

2. Then, we need to get the 'Session' object from the 'SessionFactory'.

Session session = HibernateUtilities.getSessionFactory().openSession();

3. Next, we use this 'Session' object and begin a transaction.

session.beginTransaction();

4. After that, we create an 'Employee' object, assign some values to it. Then we use the 'save()' method of the 'Session' to save the object to the database.

Employee employee = new Employee();
employee.setId(1);
employee.setName("Joe");
session.save(employee);

5. Then we commit the transaction which will finally commit the 'Employee' data to the database. And close the 'Session'.

session.getTransaction().commit();
session.close();

So, the steps are simple.


1. Open a 'Session' from the 'SessionFactory'.

2. Then start a 'transaction' using that 'Session'.

3. Post which create an 'Employee' object, put values to it and then save the 'Employee' object using the 'save()' method of 'Session'.

4. Finally, commit the transaction using the 'commit()' method of 'Session'.

We need to keep in mind that whatever operations we perform(like saving to DB), it should be inside the 'transaction' of a 'Session'. In other words the operation should be inside

session.beginTransaction() and session.getTransaction().commit().