tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Hibernate > Basic > Difference between Load and Get

Difference between Load and Get 

The following example shows difference between load and get operations. Refer first example for the configuration and mapping.

  • Get
    1. Use if you are not sure that the requested unique id exists.
    2. Returns null if the requested unique id doesn't exist.
    3. Returns the actual object immediately if available.
  • Load
    1. Use if you are sure that the requested unique id exists.
    2. Throws org.hibernate.ObjectNotFoundException if the requested unique id doesn't exist.
    3. Returns a proxy by default and actual object retrieval is delayed until its really required.
File Name  :  
com/bethecoder/tutorials/hibernate/basic/tests/LoadAndGetTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.hibernate.basic.tests;

import org.hibernate.Session;
import com.bethecoder.tutorials.hibernate.basic.Company;
import com.bethecoder.tutorials.hibernate.basic.util.HibernateUtil;

public class LoadAndGetTest {

  private static Integer NON_EXISTING_COMPANY_ID = new Integer(23456789);
  /**
   @param args
   */
  public static void main(String[] args) {

    getCompany();
    loadCompany();
  }

  private static void loadCompany() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Company company = null;
    
    try {
      company = (Companysession.load(Company.class, NON_EXISTING_COMPANY_ID);
      System.out.println("company : " + company);
    catch (org.hibernate.ObjectNotFoundException e) {
      System.err.println(e);
    }
    
    session.getTransaction().commit();
    session.close();
  }
  
  private static void getCompany() {

    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
  
    Company company = (Companysession.get(Company.class, NON_EXISTING_COMPANY_ID);
    System.out.println("company : " + company);
    
    session.getTransaction().commit();
    session.close();
  }
}
   

It gives the following output,
company : null
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: 
	[com.bethecoder.tutorials.hibernate.basic.Company#23456789]



 
  


  
bl  br