Search This Blog

Tuesday, 14 August 2012

fetch = join for non-Collection Association

In the previous post we applied the join fetch strategy for collections. Now I shall apply them to a many-to-one and a one-to-one association.
I shall consider a variant of the Book class again.
public class DetailedBook {
    private String name;
    private Integer id;
    private Shelf shelf;
    private BookDetails details;
The Detailed Book has a one-to-one association(shared foreign key) with BookDetails and a many-to-one association with Shelf.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping package="">
    <class name="DetailedBook" table="DETAILED_BOOK">
        <id name="id" type="integer">
            <column name="ID" />
            <generator class="native" />
        <property name="name" type="string">
            <column name="Name" length="50" not-null="true" />
        <many-to-one name="shelf" class="Shelf" foreign-key="DETAILED_BOOK_FK1" 
             fetch="join" not-null="true">
            <column name="shelf_id"></column>
        <many-to-one name="details" class="BookDetails" unique="true" cascade = "all"
            foreign-key="DETAILED_BOOK_FK2" fetch="join" not-null="true">
            <column name="details_id"></column>
As can be seen a join strategy has been applied to eagerly fetch the two associations.
I now executed a code to load a Book from the database.
public static void testLoad() {
    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    DetailedBook book1 = (DetailedBook) session.load(DetailedBook.class, bookId);
    System.out.println("Name is " + book1.getName() + " and shelf is"
            + book1.getShelf().getCode() + ". Book author is " +book1.getDetails().getAuthor());
The output logs indicate that only a single query as executed to load the DetailedBook object and the associations:
    /* load com.association.join.DetailedBook */ 
        detailedbo0_.ID as ID0_2_,
        detailedbo0_.Name as Name0_2_,
        detailedbo0_.shelf_id as shelf3_0_2_,
        detailedbo0_.details_id as details4_0_2_,
        shelf1_.ID as ID1_0_,
        shelf1_.CODE as CODE1_0_,
        bookdetail2_.ID as ID2_1_, as author2_1_,
        bookdetail2_.description as descript3_2_1_ 
        DETAILED_BOOK detailedbo0_ 
    left outer join
        SHELF shelf1_ 
            on detailedbo0_.shelf_id=shelf1_.ID 
    left outer join
        BOOK_DETAILS bookdetail2_ 
            on detailedbo0_.details_id=bookdetail2_.ID 
Name is Simply Fly and shelf isSH001. Book author is Gopinath

No comments:

Post a Comment