I have a driver class called GrouptTest (See listings section below). I am trying to explore the lazy loading feature in hibernate. I have a group object that has a collection of stories.
I have one Hibernate session created for the Driver class by making a call below:
Code:
....
HibernateSession.openSession();
....
....
// My dao objects use the same session for the execution of the test class
....
....
HibernateSession.closeSession();
....
I get a Group object by name, by doing:
Code:
...
Group group = groupDAO.findGroup("accounting", false);
...
I then get a List of stories by making a call to:
Code:
...
List stories = group.getStories();
if(stories != null)
...
THE PROBLEM is that I am facing is that when i make a call to findGroup (See code below), my group object is returned with the story objects populated in the collection inside it.?????? (NOTE: This happens before the call to group.getStories()). Why does this happen even when I specify lazy="true" in my Group.hbm.xml file?????
Listngs:
Code:
public class GroupTest
{
public static void main(String [] args) throws HibernateException
{
HibernateSession.openSession();
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.DS);
InitializeDAO initDAO = daoFactory.getInitializeDAO();
boolean flag = initDAO.initializeDS();
if(flag == false)
{
System.out.println("Could not initialize data source");
System.exit(0);
}
GroupDAO groupDAO = daoFactory.getGroupDAO();
Group sp = new Group("accounting");
ArrayList list = new ArrayList();
for(int i = 0; i < 1000; i++)
{
list.add(new Story("Story Number: " + i));
}
sp.setStories(list);
groupDAO.insertGroup(sp);
Group group = groupDAO.findGroup("accounting");
if(group != null)
{
System.out.println("Group name of the retrieved group is: " + group.getName());
List stories = group.getStories();
if(stories != null)
{
Iterator iter = stories.iterator();
while(iter.hasNext())
{
Story s = (Story)iter.next();
System.out.println("\tStory: " + s.getInfo());
}
}
}
else
System.out.println("There is no Group present by that name");
HibernateSession.closeSession();
}
}
Code:
...
...
<hibernate-mapping>
<class name="med.allegro.sp.persistent.Group" table="grouptable" discriminator-value="parent">
<id name="id" unsaved-value="0">
<generator class="native"/>
</id>
<discriminator column="type"/>
<list name="stories" cascade="all" lazy="true">
<key column="parent_id"/>
<index column="idx"/>
<one-to-many class="med.allegro.sp.persistent.Story"/>
</list>
...
...
Code:
public Group findGroup(String name)
{
Group group = null;
try
{
Session session = HibernateSession.currentSession();
Query q = session.createQuery("from med.allegro.sp.persistent.Group as groups where groups.name=:gname");
q.setString("gname", name);
group = (Group)q.list().get(0);
}
catch(Exception e)
{
e.printStackTrace();
}
return group;
}