-->
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.  [ 5 posts ] 
Author Message
 Post subject: NoSuchElementException
PostPosted: Wed Aug 16, 2006 9:25 pm 
Beginner
Beginner

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

Mapping documents:
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"
      />
   </class>
</hibernate-mapping>



Code between sessionFactory.openSession() and session.close():
Code:
   public Category findCategoryByName(Session session, String name)throws Exception
   {
      List results = session.createQuery("from Category as c where c.name='" + name +"'").list();
      return (Category)results.iterator().next();
   }
   

Full stack trace of any exception that occurs:

[java] Exception in thread "main" java.util.NoSuchElementException
[java] at java.util.AbstractList$Itr.next(AbstractList.java:427)
[java] at ergal.BusinessService.findCategoryByName(Unknown Source)
[java] at ergal.BusinessService.modifyCategoryAssociation(Unknown Sourc
e)
[java] at ergal.BusinessService.test(Unknown Source)
[java] at ergal.BusinessService.main(Unknown Source)
[java] Java Result: 1


Name and version of the database you are using:mysql 5.0.22

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<Category> childCategories = new HashSet<Category>(0);
     private Category parentCategory;

     // Constructors

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

    /** full constructor */
    public Category(String name, Category parentCategory, Set<Category> 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<Category> getChildCategories()
    {
        return this.childCategories;
    }
   
    public void setChildCategories(Set<Category> childCategories)
    {
        this.childCategories = childCategories;
    }
    public Category getParentCategory()
    {
        return this.parentCategory;
    }
   
    public void setParentCategory(Category parentCategory)
    {
        this.parentCategory = parentCategory;
    }




}





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 saveCategoryWithCaseCade()throws Exception
   {
      Session session = sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         
         Category foodCategory=new Category("food", null, new HashSet());
         Category fruitCategory=new Category("fruit", null, new HashSet());
         Category vegetableCategory=new Category("vegetable", null, new HashSet());
         Category appleCategory=new Category("apple", null, new HashSet());
         Category orangeCategory=new Category("orange", null, new HashSet());
         Category tomatoCategory=new Category("tomato", null, new HashSet());
         
         foodCategory.getChildCategories().add(fruitCategory);
         fruitCategory.setParentCategory(foodCategory);
         
         foodCategory.getChildCategories().add(vegetableCategory);
         vegetableCategory.setParentCategory(foodCategory);
         
         fruitCategory.getChildCategories().add(appleCategory);
         appleCategory.setParentCategory(fruitCategory);
         
         fruitCategory.getChildCategories().add(orangeCategory);
         orangeCategory.setParentCategory(fruitCategory);
         
         fruitCategory.getChildCategories().add(tomatoCategory);
         tomatoCategory.setParentCategory(fruitCategory);
         
         session.save(foodCategory);
         tx.commit();
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }
   
   public void modifyCategoryAssociation()throws Exception
   {
      Session session=sessionFactory.openSession();
      Transaction tx=null;
      try
      {
         tx=session.beginTransaction();
         
         Category tomatoCategory=findCategoryByName(session,"tomato");
         Category fruitCategory=findCategoryByName(session, "fruit");
         Category vegetableCategory=findCategoryByName(session, "vagetable");
         
         vegetableCategory.getChildCategories().add(tomatoCategory);
         tomatoCategory.setParentCategory(vegetableCategory);
         
         fruitCategory.getChildCategories().remove(tomatoCategory);
         
         tx.commit();
         
      }
      catch(Exception e)
      {
         if(tx!=null)
         {
            tx.rollback();
         }
         throw e;
      }
      finally
      {
         session.close();
      }
   }
   
   public Category findCategoryByName(Session session, String name)throws Exception
   {
      List results = session.createQuery("from Category as c where c.name='" + name +"'").list();
      return (Category)results.iterator().next();
   }
   
   public void test()throws Exception
   {
      saveCategoryWithCaseCade();
      modifyCategoryAssociation();      
   }
   
   public static void main(String[] args)throws Exception
   {
      new BusinessService().test();
      sessionFactory.close();
   }
}



There is data in my database already after execute the saveCategoryWithCaseCade() method

How could the exception occur?


Top
 Profile  
 
 Post subject:
PostPosted: Wed Aug 16, 2006 11:16 pm 
Expert
Expert

Joined: Thu Dec 23, 2004 9:08 pm
Posts: 2008
The main problem is that you're not guarding iterator().next() with iterator().hasNext().

The reason that you're getting the exception is that you save a vegetable, but then load a vagetable. vagetable != vegetable, so there's no items in that list, hence the exception. Which would have been prevented if you had protected next() with hasNext(), as you are required to do by Iterator's contract.

Two other points:
  1. the "find X as x" syntax is deprecated. Use "find X x" instead.
  2. Don't build query strings like that. Use positional or named parameters. This is better:
Code:
List results = session.createQuery("from Category where name=:name").setString("name", name).list();

_________________
Code tags are your friend. Know them and use them.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 17, 2006 12:41 am 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
Thx for your help very much
But there is still something I don't understand

1 what's the meaning that you told me vagetable. vagetable != vegetable
the
Code:
findCategoryByName(session, "vagetable")

didn't returns vegetable ?

2 when I modify the code

Code:
public Category findCategoryByName(Session session, String name)throws Exception
   {
      List results = session.createQuery("from Category as c where c.name='" + name +"'").list();
      return (Category)results.iterator().next();
   }


to this
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;
   }


there is a new exception
Code:
     [java] Exception in thread "main" java.lang.NullPointerException
     [java]     at ergal.BusinessService.modifyCategoryAssociation(Unknown Sourc
e)
     [java]     at ergal.BusinessService.test(Unknown Source)
     [java]     at ergal.BusinessService.main(Unknown Source)
     [java] Java Result: 1

why ?
I think the problem due to
Code:
vegetableCategory.getChildCategories()

vegetableCategory doesn't has ChildCategories
isn't it ?

I know you are a master
plz !! help me !
someone help !

How to resolve it ? [/code]


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 17, 2006 1:37 am 
Expert
Expert

Joined: Thu Dec 23, 2004 9:08 pm
Posts: 2008
I was referring to the fact that in your posted code, you have these two lines:
Code:
         Category vegetableCategory=new Category("vegetable", null, new HashSet());
         Category vegetableCategory=findCategoryByName(session, "vagetable");
You've set up a category "vegetable", then you search for a category "vagetable". That's not going to find anything. findCategoryByName requires that you find at least one item in the category. You won't, hence your original exception.

The new exception is because vegetableCategory is null. Because vegetableCategory was loaded using the search string "vagetable", but it was created using the string "vegetable".

It's what we know in the industry as a "typo".

_________________
Code tags are your friend. Know them and use them.


Top
 Profile  
 
 Post subject:
PostPosted: Thu Aug 17, 2006 2:01 am 
Beginner
Beginner

Joined: Sun Aug 13, 2006 8:48 am
Posts: 23
I'm so sorry that wasting your time and made this joke

I didn't catch on at the first time
I got it I will be careful next time
Thank you again master and it's really felicity that the forum get possession of you


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 5 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.