-->
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.  [ 4 posts ] 
Author Message
 Post subject: How to print results NON-iteratively (i.e. 1 result)?
PostPosted: Fri May 04, 2007 5:03 pm 
Newbie

Joined: Fri May 04, 2007 3:43 pm
Posts: 18
Currently, I'm only familiar with the iterative method of looping through all results from an HQL query. This seems like a lot of code if there is only one result; can someone steer me to a better alternative to the following code? Assume that the HQL query will return only 1 result. I want to print the resulting column (ACTIONS):

Code:
// perform query and count the results
      List result = session.createQuery("from Users as user where NAME='"+name+"'").list();
      if (result.size() == 1)
      {
         for (Iterator iter = result.iterator(); iter.hasNext();)
         {
            Users user = (Users) iter.next();
            ret = user.getActions();     
         }
      }
[/code]


Top
 Profile  
 
 Post subject:
PostPosted: Fri May 04, 2007 5:27 pm 
Expert
Expert

Joined: Wed Apr 06, 2005 5:03 pm
Posts: 273
Location: Salt Lake City, Utah, USA
Code:
Users user = (Users) session.createQuery("from Users as user where NAME='"+name+"'").uniqueResult();

uniqueResult() will throw an exception if the query returns more than one row, so be careful.

as a side note, you should make your query static, and use variables, i.e.

Code:
Users user = (Users) session.createQuery("from Users as user where NAME=:name).setString("name",name).uniqueResult();

that allows your query to be cached, which is better for performance.

_________________
nathan


Top
 Profile  
 
 Post subject:
PostPosted: Fri May 04, 2007 8:50 pm 
Newbie

Joined: Fri May 04, 2007 3:43 pm
Posts: 18
Thanks for the response. As for your suggestion, how does one come upon that information? What I mean is, where can I learn tips like that to make my code more efficient?


Top
 Profile  
 
 Post subject:
PostPosted: Fri May 04, 2007 9:21 pm 
Expert
Expert

Joined: Wed Apr 06, 2005 5:03 pm
Posts: 273
Location: Salt Lake City, Utah, USA
I think the Hibernate book gets into it. Or you can pick up things like that by searching in and reading this forum (and posting questions).

_________________
nathan


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