Calling a method directly or through Reflection is going to initialize the association.
To prove this, I modified your test to this:
Code:
@Test
public void testGetByParentIdLazy() throws Exception {
CategoryDAO<Category> categoryCategoryDAO = new CategorySqlHibernateDAO();
prepare();
List<Category> result = categoryCategoryDAO.getByParentIdLazy(0);
Assert.assertTrue(result.size() == 1);
Category category = result.get( 0 );
System.out.println("Fetch by reflection");
Object children = category.getClass().getMethod( "getChildren" ).invoke( category );
System.out.println(children);
}
and the output is:
Code:
Hibernate:
select
category0_.categoryId as category1_0_,
category0_.categoryName as category2_0_,
category0_.categoryImage as category3_0_,
category0_.categoryParentId as category4_0_
from
Category category0_
where
categoryParentId=?
Fetch by reflection
Hibernate:
select
children0_.categoryParentId as category4_0_0_,
children0_.categoryId as category1_0_0_,
children0_.categoryId as category1_0_1_,
children0_.categoryName as category2_0_1_,
children0_.categoryImage as category3_0_1_,
children0_.categoryParentId as category4_0_1_
from
Category children0_
where
children0_.categoryParentId=?
[com.electronic.commerce.models.Category@8cfb95e3]
So,
1. The Category select is executed and the children is not initialized
2. Then comes the "Fetch by reflection"
3. We access the children through reflection and Hibernate generates the child select so initialize the lazy collection
N.B. When it comes to initializing Proxies, you need to use logging because debugging will always cause the Proxy to be initialized since the IDE tries to analyze the state of all fields.