-->
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.  [ 2 posts ] 
Author Message
 Post subject: Query.list() return type
PostPosted: Tue Mar 22, 2011 1:26 pm 
Newbie

Joined: Tue Mar 22, 2011 10:44 am
Posts: 11
Hi
I am trying to do simple query (get all names) on the table using Hibernate. For that I write a simple business logic function getAllName() as follow:

Code:
public ArrayList<String> getAllAgencyName() {
        ArrayList<String> agencyNames = new ArrayList<String>();
        try{
            Transaction tx = session.beginTransaction();
            Query q = session.createQuery("FROM Agency");
            agencyNames = (ArrayList<String>) q.list();
            for(String a: agencyNames){
                System.out.println("Agency Name: " + a);
            }
        }catch(Exception e){
            log.error("Error in getting all agency name: " + e);
        }
        return agencyNames;
    }


Now when I run the application it give me an error saying
Code:
java.lang.ClassCastException: mypkg.pojo.Agency cannot be cast to java.lang.String

while entering the for loop.

What am I doing wrong?


Top
 Profile  
 
 Post subject: Re: Query.list() return type
PostPosted: Tue Mar 22, 2011 2:39 pm 
Expert
Expert

Joined: Wed Mar 03, 2004 6:35 am
Posts: 1240
Location: Lund, Sweden
Code:
agencyNames = (ArrayList<String>) q.list();


is not correct. Your query is returing a list of Agency objects and it may not be an ArrayList but another implementation of the List interface. This should work (but you have to change the rest of your code also).

Code:
List<Agency> agencies = (List<Agency>)q.list();


Another option is that you only specify the 'name' property in a select clause (assuming that your Agency has a name property which is a String):

Code:
Query q = session.createQuery("select a.name from Agency a");


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