Hi. I would like to load the elements in a collection using a different hibernate session then the session used to retrieve the hibernate collection.
In an initial request I want to store a collection in a web session, but I only need the elements in a different request (which uses a different hibernate session). I would prefer not to initialize the collection until needed.
I expected that
Code:
newSession.lock(children, LockMode.NONE);
would do this, but this fails with a MappingException. What is the right way to do this?
I have included a small test program below that demonstrates what I want to do exactly.
version: hibernate 2.1.3
-- attempt
Code:
public class TestLazyCollection {
public static void main(String[] args) {
Collection children = null;
SessionFactory sessionFactory = null;
try {
Configuration configuration = new Configuration().configure(TestLazyCollection.class.getResource("hibernate.cfg.xml"));
sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
TreeItem parent = (TreeItem) session.load(TreeItem.class, new Integer(1));
children = parent.getChildren();
session.close();
} catch (HibernateException e) {
e.printStackTrace();
}
// --- request boundary
try {
Session newSession = sessionFactory.openSession();
// fails with MappingException: No persister for: net.sf.hibernate.collection.Set
newSession.lock(children, LockMode.NONE);
System.out.println(children);
newSession.close();
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
-- mapping
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="com.betterbe.test.hibernate.TreeItem"
table="tree" mutable="false">
<id name="id" column="id" type="int"><generator class="assigned" /></id>
<property name="name" type="string" access="property" column="name" />
<set name="children" lazy="true">
<key column="parent" />
<one-to-many class="com.betterbe.test.hibernate.TreeItem" />
</set>
</class>
</hibernate-mapping>
-- bean
Code:
public class TreeItem {
private int id;
private String name;
private Collection children;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public void setChildren(Collection children) { this.children = children; }
public Collection getChildren() { return children; }
public String toString() { return name; }
}