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




Hibernate - Retrieving from Database

Now, since we are able to save data to the database using Hibernate. Then there should also be a way to retrieve from database. Let us see the example below:

We will be taking the same Employee class:


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

Just like the previous example we will be following the same steps with added code to fetch data.



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.beginTransaction();

   Employee employee1 = (Employee) session.get(Employee.class,1);
   System.out.println("Employee ID is : "+employee1.getId());
   System.out.println("Employee Name is : "+employee1.getName());

   session.getTransaction().commit();

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

So, as we can see above, saving 'Employee' data is within a transaction of a 'Session'. Now, when we are trying to fetch data from the database, we are starting a new transaction using 'Session' object.

session.beginTransaction();


Fetching data from the database is quite simple.

Employee employee1 = (Employee) session.get(Employee.class,1);

In the get() method of 'Session', we pass the class name and the primary key of that class. And the entire record associated to the primary key is returned as an 'Employee' object.


Let's consider the below value in EMPLOYEE table:


ID NAME
1 Joe

Now, when we pass '1' as the primary key in 'session.get(Employee.class,1)', we get the 'Employee' object with values 1 and Joe as 'id' and 'name'.