-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 posts ] 
Author Message
 Post subject: failed to lazily initialize a collection of role
PostPosted: Thu Aug 17, 2006 2:53 pm 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
Hibernate version: 3.2

Mapping documents:

Category.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">


<hibernate-mapping>

   <class name="ergal.Category" table="CATEGORIES" lazy="true">
      <id name="id" type="long" column="ID">
         <generator class="increment" />
      </id>
   
      <property name="name" type="string">
         <column name="NAME" length="15" />
      </property>
      <set
         name="childCategories"
         cascade="save-update"
         inverse="true"
         >      
         <key column="CATEGORY_ID" />
         <one-to-many class="ergal.Category" />
      </set>
      
      <many-to-one
         name="parentCategory"
         column="CATEGORY_ID" 
         class="ergal.Category"
         cascade="save-update"
      />
   </class>
</hibernate-mapping>


Code between sessionFactory.openSession() and session.close():

Code:
   public void saveVegetableCategory()throws Exception
   {
      tx=session.beginTransaction();
      Category foodCategory=findCategoryByName(session, "food");
      Category vegetableCategory=new Category("vegetable", null, new HashSet());
      foodCategory.addChildCategory(vegetableCategory);

   }


Full stack trace of any exception that occurs:

[java] Exception in thread "main" org.hibernate.LazyInitializationException
: failed to lazily initialize a collection of role: ergal.Category.childCategori
es, no session or session was closed
[java] at org.hibernate.collection.AbstractPersistentCollection.throwLa
zyInitializationException(AbstractPersistentCollection.java:358)
[java] at org.hibernate.collection.AbstractPersistentCollection.throwLa
zyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
[java] at org.hibernate.collection.AbstractPersistentCollection.initial
ize(AbstractPersistentCollection.java:343)
[java] at org.hibernate.collection.AbstractPersistentCollection.write(A
bstractPersistentCollection.java:183)
[java] at org.hibernate.collection.PersistentSet.add(PersistentSet.java
:168)

Name and version of the database you are using:mysql5.0.22

I have wasted much time on this exception(more than 6 hours)

the code
Category.java
Code:
package ergal;
// Generated 2006-8-17 4:35:53 by Hibernate Tools 3.2.0.beta6a


import java.util.HashSet;
import java.util.Set;
import java.io.Serializable;

/**
* Category generated by hbm2java
*/
public class Category  implements java.io.Serializable {

    // Fields   

     private long id;
     private String name;
     private Set childCategories;
     private Category parentCategory;

     // Constructors

    /** default constructor */
    public Category() {}
   
    public Category(Set childCategories)
    {
       this.childCategories = childCategories;
    }

    /** full constructor */
    public Category(String name, Category parentCategory, Set childCategories)
    {
       this.name = name;
       this.childCategories = childCategories;
       this.parentCategory = parentCategory;
    }
   
   
    // Property accessors
    public long getId()
    {
        return this.id;
    }
   
    public void setId(long id)
    {
        this.id = id;
    }
    public String getName()
    {
        return this.name;
    }
   
    public void setName(String name)
    {
        this.name = name;
    }
    public Set getChildCategories()
    {
        return this.childCategories;
    }
   
    public void setChildCategories(Set childCategories)
    {
        this.childCategories = childCategories;
    }
    public Category getParentCategory()
    {
        return this.parentCategory;
    }
   
    public void setParentCategory(Category parentCategory)
    {
        this.parentCategory = parentCategory;
    }

    public void addChildCategory(Category category)
    {
       if(category == null)
       {
          throw new IllegalArgumentException("Can't add a null Category as child.");
       }
       if(category.getParentCategory() !=  null)
       {
          category.getParentCategory().getChildCategories().remove(category);
       }
       category.setParentCategory(this);
       this.getChildCategories().add(category);
    }


}



BusinessService.java

Code:
package ergal;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;

public class BusinessService
{
   public static SessionFactory sessionFactory;
   static
   {
      try
      {
         Configuration config = new Configuration();
         sessionFactory =config.configure().buildSessionFactory();
      }
      catch(Exception e)
      {
         e.printStackTrace();
      }
   }
   
   public void saveFoodCategory()throws Exception
   {
      
      Category foodCategory=new Category("food", null, new HashSet());
      Category fruitCategory=new Category("fruit", null, new HashSet());
      Category appleCategory=new Category("apple", null, new HashSet());
            
      foodCategory.addChildCategory(fruitCategory);      

      fruitCategory.addChildCategory(appleCategory);         
      saveOrUpdate(foodCategory);   
   }
   
   public void navigateCategories()throws Exception
   {
      Category fruitCategory=findCategoryByName("fruit");
      HashSet categories=new HashSet();
      navigateCategories(fruitCategory, categories);
      for(Iterator it=categories.iterator(); it.hasNext();)
      {
         System.out.println(((Category)it.next()).getName());
      }   
   }
   
   private void navigateCategories(Category category,Set categories)
   {
      if(categories.contains(category) || category==null)
         return;
      categories.add(category);
      
      navigateCategories(category.getParentCategory(), categories);
      
      Set childCategories = category.getChildCategories();
      if(childCategories==null)
         return;
      for(Iterator it=childCategories.iterator(); it.hasNext();)
      {
         navigateCategories((Category)it.next(), categories);
      }
   }
   
   public void saveVegetableCategory()throws Exception
   {

      Category foodCategory=findCategoryByName("food");
      Category vegetableCategory=new Category("vegetable", null, new HashSet());
      foodCategory.addChildCategory(vegetableCategory);
                  saveOrUpdate(vegetableCategory);
         }
   
   public void updateVegetableCategory()throws Exception
   {
      Category vegetableCategory=findCategoryByName("vegetable");
      vegetableCategory.setName("green vegetable");
      Category tomatoCategory=new Category("tomato", null, new HashSet());
      vegetableCategory.addChildCategory(tomatoCategory);
      saveOrUpdate(vegetableCategory);
   }
   
   public void saveOrangeCategory()throws Exception
   {
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         Category fruitCategory=findCategoryByName(session,"fruit");
         Category orangeCategory=new Category("orange", null, new HashSet());
         fruitCategory.addChildCategory(orangeCategory);
         
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }
   
   public void saveOrUpdate(Object bject)throws Exception
   {
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         session.saveOrUpdate(bject);
         
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }
   
   public Category findCategoryByName(String name)throws Exception
   {
      Category c=new Category();
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         c = findCategoryByName(session, name);
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
      return c;
   }
   
   public Category findCategoryByName(Session session, String name)throws Exception
   {
      Category c=new Category();
      List results = session.createQuery("from Category where name=:name").setString("name", name).list();
      Iterator it = results.iterator();
      while(it.hasNext())
      {
         c = (Category)it.next();      
      }
      return c;
   }
   
   public void test()throws Exception
   {
      saveFoodCategory();
      saveOrangeCategory();
      saveVegetableCategory();
      updateVegetableCategory();
      navigateCategories();   
   }
   
   public static void main(String[] args)throws Exception
   {
      new BusinessService().test();
      sessionFactory.close();
   }
}


in the mothod test() saveFoodCategory() and saveOrangeCategory()
could work normally and there 4 items in my database
There are food , fruit , apple and orange
but when the saveVegetableCategory() is quering
it always has this exception
[java] Exception in thread "main" org.hibernate.LazyInitializationExceptio
: failed to lazily initialize a collection of role: ergal.Category.childCategor
es, no session or session was closed
[java] at org.hibernate.collection.AbstractPersistentCollection.throwL
zyInitializationException(AbstractPersistentCollection.java:358)
[java] at org.hibernate.collection.AbstractPersistentCollection.throwL
zyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
[java] at org.hibernate.collection.AbstractPersistentCollection.initia
ize(AbstractPersistentCollection.java:343)
[java] at org.hibernate.collection.AbstractPersistentCollection.write(
bstractPersistentCollection.java:183)
[java] at org.hibernate.collection.PersistentSet.add(PersistentSet.jav
:168)

when i modify the modify saveVegetableCategory()

Code:
   public void saveVegetableCategory()throws Exception
   {

      Category foodCategory=findCategoryByName(session, "food");
      Category vegetableCategory=new Category("vegetable", null, new HashSet());
      foodCategory.addChildCategory(vegetableCategory);
                  saveOrUpdate(vegetableCategory);
         }      


to this

Code:
   public void saveVegetableCategory()throws Exception
   {

      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         Category foodCategory=findCategoryByName(session,"food");
         Category vegetableCategory=new Category("vegetable", null, new HashSet());
         foodCategory.addChildCategory(vegetableCategory);
         
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }   


it could work

why ?

somebody help

Thx


Last edited by rainytooo on Fri Aug 18, 2006 4:52 am, edited 2 times in total.

Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 3:27 am 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
....................
why?
TT


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 3:57 am 
Expert
Expert

Joined: Thu Sep 22, 2005 10:29 am
Posts: 285
Location: Almassera/Valencia/Spain/EU/Earth/Solar system/Milky Way/Local Group/Virgo Supercluster
I think you have posted saveVegetableCategory() function incorrectly.

Where does 'session' come from in that function?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 5:06 am 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
Thank you

I modify this method

But this is my fault when paste the code

it still has this exception


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 5:48 am 
Expert
Expert

Joined: Thu Sep 22, 2005 10:29 am
Posts: 285
Location: Almassera/Valencia/Spain/EU/Earth/Solar system/Milky Way/Local Group/Virgo Supercluster
Ok, but What is the real code?


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 6:51 am 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
Ok
simply
the problem is that
it's no problem when use the method "public void saveOrangeCategory()"
it use the method
Code:
public Category findCategoryByName(Session session, String name)throws Exception
   {
      Category c=new Category();
      List results = session.createQuery("from Category where name=:name").setString("name", name).list();
      Iterator it = results.iterator();
      while(it.hasNext())
      {
         c = (Category)it.next();       
      }
      return c;
   }

but in the method
Code:
 
   public void saveVegetableCategory()throws Exception
   {
      Category foodCategory=findCategoryByName("food");
      Category vegetableCategory=new Category("vegetable", null, new HashSet());
      foodCategory.addChildCategory(vegetableCategory);
      saveOrUpdate(vegetableCategory);
    }


it use the
Code:
public Category findCategoryByName(String name)throws Exception
   {
      Category c=new Category();
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         c = findCategoryByName(session, name);
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
      return c;
   }


and this could lead the exeption

Code:
[java] Exception in thread "main" org.hibernate.LazyInitializationExceptio
: failed to lazily initialize a collection of role: ergal.Category.childCategor
es, no session or session was closed
[java] at org.hibernate.collection.AbstractPersistentCollection.throwL
zyInitializationException(AbstractPersistentCollection.java:358)
[java] at org.hibernate.collection.AbstractPersistentCollection.throwL
zyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
[java] at org.hibernate.collection.AbstractPersistentCollection.initia
ize(AbstractPersistentCollection.java:343)
[java] at org.hibernate.collection.AbstractPersistentCollection.write(
bstractPersistentCollection.java:183)
[java] at org.hibernate.collection.PersistentSet.add(PersistentSet.jav
:168)

I don't know why it told me that "no session or session was closed"

Thx !
plz help me
I am a Newbie


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 7:33 am 
Expert
Expert

Joined: Thu Sep 22, 2005 10:29 am
Posts: 285
Location: Almassera/Valencia/Spain/EU/Earth/Solar system/Milky Way/Local Group/Virgo Supercluster
You get foodCategory with findCategoryByName that opens and close a session.

Then you call foodCategory.addChildCategory(vegetableCategory);
Inside this method there's a call to this.getChildCategories().add(category); that in fact is translated to foodCategory.getChildCategories().add(vegetableCategory); but in that instant the session used to get foodCategory has already been closed. That throws the exception.


I suggest you not to open and close so many sessions. Don't make finders and that kind of methods responsibles of opening and closing the session.

Please, don't forget to rate.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Aug 18, 2006 11:12 am 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
Thank u very much!

I change the saveVegetableCategory() and updateVegetableCategory()
to this
Code:
   public void saveVegetableCategory()throws Exception
   {
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         Category foodCategory=findCategoryByName(session, "food");
         Category vegetableCategory=new Category("vegetable", null, new HashSet());
         foodCategory.addChildCategory(vegetableCategory);
         session.saveOrUpdate(vegetableCategory);
         
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }
   
   public void updateVegetableCategory()throws Exception
   {
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         Category vegetableCategory=findCategoryByName(session, "vegetable");
         vegetableCategory.setName("green vegetable");
         Category tomatoCategory=new Category("tomato", null, new HashSet());
         vegetableCategory.addChildCategory(tomatoCategory);
         session.saveOrUpdate(vegetableCategory);
         
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }
   


But actually I have another question
If I modify these method like this , it could run normally
but the method "findCategoryByName(String name)"
and "saveOrUpdate(Object bject)" is useless
On the other hand I must write the code

Code:
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         ......
         
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }

everytime.
So it is not my original intention

tell me what you think or how to achieve my intention with
the method "findCategoryByName(String name)" and "saveOrUpdate(Object bject)"
My problem is that I could not to close session in my original
saveVegetableCategory() function
Code:
   public void saveVegetableCategory()throws Exception
   {

      Category foodCategory=findCategoryByName("food");
      Category vegetableCategory=new Category("vegetable", null, new HashSet());
      foodCategory.addChildCategory(vegetableCategory);
      saveOrUpdate(vegetableCategory);
    }
   

so that's the point


Top
 Profile  
 
 Post subject:
PostPosted: Mon Aug 21, 2006 6:05 am 
Expert
Expert

Joined: Thu Sep 22, 2005 10:29 am
Posts: 285
Location: Almassera/Valencia/Spain/EU/Earth/Solar system/Milky Way/Local Group/Virgo Supercluster
Have a look to CaveatEmptor.

In particular to HibernateUtil class.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 9 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.