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