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"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.complex_model">
    <class name="Entity">
        <id name="id" type="integer">
            <generator class="native" />
        </id>
        <property name="data" type="string">
            <column name="DATA" />
        </property>
        <set name="children" table="CHILDREN" cascade="all" inverse="true">
            <key column="ENTITY_ID" />
            <one-to-many class="Child" />
        </set>
        <many-to-one name="masterData" class="MasterData" />
    </class>
</hibernate-mapping>
Now consider the code to load the Entity object.
static void testLoad() {
    Session session = sessionFactory.openSession();
    Entity entity = (Entity) session.load(Entity.class, 7);
    session.close();
}
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.

No comments:

Post a Comment