• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HQL Query return type

 
Ali Ekber
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on an HQL hibernate query and a simplified version of the code is below:

List messages = new ArrayList();
Session session = getSession(false);
String hqlSelect = "select id, messageText, uId from Message where uId = :userId";
Query query = session.createQuery(hqlSelect);
query.setString("userId", userId);
messages = query.list();

Iterator it = messages.iterator();
while (it.hasNext()) {
System.out.println("message -> "+ ( ((Message) ((ArrayList) it.next()).get(0)).getMessageText()));
}

I am getting ClassCast exception inside the while loop when I try to type cast the iterator to ArrayList or to Message. I think iterator is coming back as Object.

Is there any way I have the result set (List) returned as an array list of Message classes?
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

System.out.println("message -> "+ ( ((Message) ((ArrayList) it.next()).get(0)).getMessageText()));


Why are you casting to ArrayList?
Each element returned by calling iter.next() IS A Message.
(Message(it.next())).getMessageText(); should work.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hope this would work. I haven't tried it though. Even if it doesn't work. it will definitely give you a hint.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why SQL query? Try this...

 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why SQL query? Try this...

You mean HQL? But you make a good point, using Criteria in stead of HQL is a better way to go.
 
Adeel Ansari
Ranch Hand
Posts: 2874
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Paul Sturrock:
You mean HQL?


O'Yeah. Actually, when it starts with a select, it looks SQL to me. You know such queries - without any particular column/s to project - which starts with a from looks more HQL, IMO.
[ October 20, 2008: Message edited by: Adeel Ansari ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic