Question

<!-- Clasa Proiect-->
<class catalog="tema3" name="com.tema3.tables.Proiect" table="proiect" lazy="false">
    <id column="proiect_id" name="id">
        <generator class="native"/>
    </id>
    <property name="nume"  type="text" />

    <set name="itemList" table="proiect_item" fetch="select">
        <key column="proiect_id"/>
        <many-to-many column="item_id" unique="true" class="com.tema3.tables.Item"/>
    </set>
</class>    </class>

that is my mapping class.
the code in wich i call an instantiation is :

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
 Query q = session.createQuery("from Proiect");
 List<Proiect> lists = HibernateUtil.listAndCast(q);
 session.getTransaction().commit();
 obj = lists;

and this is listandCastMethod:

public static <T> List<T> listAndCast(Query q) {
    @SuppressWarnings("unchecked")
    List list = q.list();
    return list;
}

And i keep geting a :

May 2, 2011 4:38:03 PM org.hibernate.LazyInitializationException <init>
SEVERE: failed to lazily initialize a collection of role: com.tema3.tables.Proiect.itemList, no session or session was closed
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.tema3.tables.Proiect.itemList, no session or session was closed
 at   org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)

but the thing is that the fields of Proiect class are populated except the Items set where i get this exception, but i want the items set to be populated.How can i do that?

Was it helpful?

Solution 2

I found the answer.It needs to add to the set declaration in the XML the property lazy="false"

OTHER TIPS

Initialize the set of items inside the listAndCast(Query q) method before returning or calling a transaction.commit(). This can be done by calling any of the accessors on an element from the set of items. This will force hibernate to initialize the set of items rather than returning a proxy list.

EDIT

 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 Query q = session.createQuery("from Proiect");
 List<Project> lists = HibernateUtil.listAndCast(q);
 if(lists != null && lists.size() > 0) {
    Set<Item> s = lists.get(0).getItemList();
    Iterator iter = s.iterator();
    while(iter.hasNext()) {
       Item item = iter.next();
       item.getSomething();
       break;
    }
 }
 session.getTransaction().commit();
 obj = lists;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top