Fetching an object from the database

Now we will take a look at how to fetch objects using a Session. Here, we will also see how to get only one record using the primary key column. We override a toString() method in the Employee and Department classes so that it's easy to display the data within an object, as shown in the following code:

@Override
    public String toString() {
      return "
Employee"
      + "
 id: " + this.getId()
      + "
 first name: " + this.getFirstName()
      + "
 salary: " + this.getSalary()
      + "
 department: " + this.getDepartment().getDeptName();
    }

How to do it…

Here, we are trying to get an employee having id equals 1.

The equivalent SQL query is as follows:

SELECT * FROM employee WHERE id=1;

Now, let's look at how to do the same using hibernate:

  1. Enter the following code to fetch an object of the employee type, where the id is 1:
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session =  sessionFactory.openSession();
    Employee employee =  (Employee) session.get(Employee.class, 1l);
    if(employee != null){
      System.out.println(employee.toString());
    }
    
    session.close(); 
    HibernateUtil.shutdown();

The output of the preceding code will be as follows:

Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?

Employee
 id: 1
 first name: yogesh
 salary: 50000.0
 department: developement

How it works…

Now, let's take a look at how the preceding code works. The first thing I want to highlight here is the query shown on the console/output window preceded by hibernate. Here, the hibernate engine internally creates a core SQL query to perform the operation that we can find in the console/output window. Hibernate internally uses JDBC to execute this query.

Another thing that needs to be highlighted is that we used the Session.get(...) method to fetch the data from the database. When you use the Session.get(...) method to fetch a record, it will perform the following actions:

  • Hit the database
  • Return a persistent instance of the given entity for the given identifier
  • Return null if no record is found

Tip

It's better to check whether the object is null or not if you are using the get() method, because get() returns null if no record is found, and you will face java.lang.NullPointerException while accessing a null object.

There's more…

Let's consider another method named load(...) to fetch the data.

Now we will take a look at how to fetch data using the load(...) method and the difference between the load() and get() methods.

The load() method works in the following manner:

  • It returns the proxy (hibernate term) object. This means that it returns the dummy object without hitting the database if the same object is found in a persistent state for the given identifier.
  • If the object is not found in the session cache, it will hit the database.
  • If no row is found in the session cache as well as in the database, then it will throw an ObjectNotFoundException error.

Let's take a look at some real-time scenarios.

Scenario 1

The record is in the session cache when load() is invoked.

Code for scenario 1

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("Employee get...");
Employee employeeGet = (Employee) session.get(Employee.class, Long.valueOf(2));
System.out.println(employeeGet.toString());
      
System.out.println("Employee load...");
Employee employeeLoad = (Employee) session.load(Employee.class,Long.valueOf(2));
System.out.println(employeeLoad.toString());

session.close(); 
HibernateUtil.shutdown();

Output for scenario 1

Employee get...
Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?

Employee
 id: 2
 first name: aarush
 salary: 35000.0
 department: developement

Employee load...

Employee
 id: 2
 first name: aarush
 salary: 35000.0
 department: developement

Explanation for scenario 1

From the output, it's clear that when the first get() method is invoked, the persisted object, Employee#2, is stored in the session cache at that time. When load() is invoked, it is directly loaded from the session; there is no need to hit the database. Here, we can show that the Select query is executed only once.

Scenario 2

The record is not in the session cache when load() is invoked.

Code for scenario 2

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("Employee get...");
Employee employeeGet = (Employee) session.get(Employee.class, new Long(1));
System.out.println(employeeGet .toString());
      
System.out.println("Employee load...");
Employee employeeLoad = (Employee) session.load(Employee.class, new Long(2));
System.out.println(employeeLoad  .toString());

session.close(); 
HibernateUtil.shutdown();

Output for scenario 2

Employee get...
Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?

Employee
 id: 1
 first name: yogesh
 salary: 50000.0
 department: developement

Employee load...
Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?

Employee
 id: 2
 first name: aarush
 salary: 35000.0
 department: developement

Explanation for scenario 2

Here, we easily determine that when get() is invoked, it hits the database and loads Employee#1. When load() is invoked, it also hits the database, because the requested Employee#2 object is not in the session cache.

Scenario 3

The record is neither in the session cache nor in the database when load() is invoked.

Code for scenario 3

SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("
Employee get...");
Employee employeeGet = (Employee) session.get(Employee.class, new Long(1));
System.out.println(employeeGet.toString());

System.out.println("
Employee load...");
Employee employeeLoad = (Employee) session.load(Employee.class, new Long(3));
System.out.println(employeeLoad .toString());

session.close(); 
HibernateUtil.shutdown();

Output for scenario 3

Employee get...
Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?

Employee
 id: 1
 first name: yogesh
 salary: 50000.0
 department: developement

Employee load...
Hibernate: select employee0_.id as id0_1_, employee0_.department as department0_1_, employee0_.firstName as firstName0_1_, employee0_.salary as salary0_1_, department1_.id as id1_0_, department1_.deptName as deptName1_0_ from employee employee0_ left outer join department department1_ on employee0_.department=department1_.id where employee0_.id=?
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [vo.Employee#3]
    at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:435)
    at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:189)
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:178)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:215)
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
    at vo.Employee_$$_javassist_1.getId(Employee_$$_javassist_1.java)
    at ch2.Load6.main(Load6.java:21)

Explanation for scenario 3

Here, get() hits the database and gets the Employee#1 object. Load tries to find Employee#3 in the session cache, but it will not find it there. So, it goes for the database and throws an org.hibernate.ObjectNotFoundException error, because Employee#3 is not in the database either.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.113.229