Search This Blog

Friday 27 July 2012

Using Interception in Hibernate -2

To continue from where we left our previous discussion, byte code interception is mainly used when we need to lazily load some of our properties.
Consider the shelf.hbm file below:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.interception">
    <class name="Shelf" table="SHELF">
        <id name="id" type="integer">
            <column name="ID" />
            <generator class="native" />
        </id>
        <property name="code" type="string" lazy = "true">
            <column name="CODE" length="50" not-null="true" />
        </property>
        <set name="allBooks" cascade="save-update" inverse="true">
            <key column="SHELF_ID" not-null="true" />
            <one-to-many class="Book" />
        </set>

    </class>
</hibernate-mapping>
As can be seen the code property has been marked as lazy. This means that the column must be fetched only when the getCode() method is called. Any SQL loading the Shelf row should not load the code column from the database. After applying byte code interception as seen in the previous example, I executed the below test code:
public static void testShelfLoad() {
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    Shelf shelf = (Shelf) session.load(Shelf.class, shelfId);
    System.out.println("book with id " + shelf.getId() + " is "  + shelf.getCode());
    transaction.commit();
    session.close();
}
The logs indicate the that lazy loading of properties was applied:
Hibernate: 
    /* load com.interception.Shelf */  
    select
        shelf0_.ID as ID1_0_ 
    from
        SHELF shelf0_ 
    where
        shelf0_.ID=?
Hibernate: 
    /* sequential select
        com.interception.Shelf */  
        select
            shelf_.CODE as CODE1_ 
        from
            SHELF shelf_ 
        where
            shelf_.ID=?
book with id 1 is SH001
As can be seen
  1. The select for Shelf table fetched all columns except code.
  2. On trying to access the code property of Shelf, a separate fetch call was executed to load the shelf's code property.

No comments:

Post a Comment