Search This Blog

Monday, 26 March 2012

get() versus load() - The Battle Continues...

In the previous two posts we saw the behavior of get() and load() methods and how it differed when session caching came into the picture.
To further test the behavior I modified the Entity class to include associations.
public class Entity {
    private Integer id;
    private String data;
    private MasterData masterData;
    private Set<Child> children = new HashSet<Child>();
//setter getters
I added a one to many relation from Entity to Child and a many to one relation between Entity and MasterData. The hbm file is now as below:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "" >
<hibernate-mapping package="com.complex_model">
    <class name="Entity">
        <id name="id" type="integer">
            <generator class="native" />
        <property name="data" type="string">
            <column name="DATA" />
        <set name="children" table="CHILDREN" cascade="all" inverse="true">
            <key column="ENTITY_ID" />
            <one-to-many class="Child" />
        <many-to-one name="masterData" class="MasterData" />
Now consider the code to load the Entity object.
static void testLoad() {
    Session session = sessionFactory.openSession();
    Entity entity = (Entity) session.load(Entity.class, 7);
I looked at the Entity object in the debug window of eclipse:
As can be seen Hibernate created a proxy for Entity and did not load any of the other associations. In fact the master reference is null and the children association refers to a normal HashSet. I executed the above code with a get call(). The XRay of the loaded object is as follows:
The get object initially only fetches the Entity object completely. For the associations, Hibernate searches the persistence cache. As it does not find them it creates proxies with the identifiers found in the Entity table. If we try to access the associations, Hibernate searches the persistence cache. If not found it then fetches them from the database.The loading of the collection is further controlled by the value of the fetch attribute in the set property. But I shall cover this in a later post.


  1. If you want your ex-girlfriend or ex-boyfriend to come crawling back to you on their knees (no matter why you broke up) you got to watch this video
    right away...

    (VIDEO) Why your ex will NEVER get back...