Difference between Load and Get
The following example shows difference between load and get operations.
Refer first example for the configuration and mapping.
Get
Use if you are not sure that the requested unique id exists.
Returns null if the requested unique id doesn't exist.
Returns the actual object immediately if available.
Load
Use if you are sure that the requested unique id exists.
Throws org.hibernate.ObjectNotFoundException if the requested unique id doesn't exist.
Returns a proxy by default and actual object retrieval is delayed until its really required.
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 = ( Company ) session.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 = ( Company ) session.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]