Hibernate 3.6 – session.get() vs session.load()

(1) , (3) :

Yes. You are right .Both the load() and get() will first check if there is an instance with the same PK is persisted in the session.

If yes , just returns that instance from the session. (It may be the proxy or the actual entity class instance)

If no , load() will create and return a proxy while get() will hit DB and returns instance of the actual entity class .

The returned object from both methods will be associated and persisted in the session afterwards.

So , whether get() or load() return proxy or the actual entity class depends on whether you use get() or load() to get the instance of the same PK in the current session for the first time.

You can proof this behaviour by performing the following test:

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

Item loadItem= (Item ) session.load(Item.class, 1);
System.out.println(loadItem.getClass().getName());

Item getItem = (Item ) session.get(Item .class, 1);
System.out.println(getItem .getClass().getName());

If it is an proxy , the printed class name will not be the same as the actual entity class name. Just change the execution order of to load() and get() to see the effect.

(2):

If load() returns a proxy , it will not access the DB during load() .The proxy will only accesses the DB if their mapped properties besides the PK are accessed and there are no instances with the same PK value is associated with the session.

After the proxy accesses the DB , the instance with the same PK of the proxy will be associated with that session .So when you get another properties from the proxy again or you use get() to get the instance for the same PK , the DB will not be accessed as the values can be found from the session.

For example:

/**Session starts***/
Item item = (Item) session.load(Item.class, new Long(1));
item.getId();  //Will not access DB as only the identifier property is access
item.getDescription(); // access the DB and initialize the proxy . After that , the item proxy is said to be initialized
item.getPrice(); //will not access DB as the item with the PK 1 can be get from the session
Item item2 = session.get(Item.class, new Long(1)) //will not access DB as the item with the PK 1 can be get from the session

If you load() an instance with the invalid ID and then access the properties or call a method (such as isInitialized()) on this proxy , ObjectNotFoundException will be thrown. So if you can catch ObjectNotFoundException , it means a proxy is loaded with an invalid ID.

If you want to ensure the ID is valid during the runtime , you should use get() and check if the returned instance is null . load() is useful when setting the foreign key constraint. See this

Leave a Comment