views:

91

answers:

5

Hello,

How can I write DAO method which will return as a result only first entry from the database. For instance lets say I'm looking at Users table and I want to retrieve only the first entry, I'd declare method like:

public User getFirstUser(){
    //method logic
}

EDIT:

User has primary key id if that matters at all.

I apologize if this question is too simple/stupid/whatever I'm beginner with Java so I'm trying new things. thank you

My attempt :

   public User getFirstUser(){
            try { 
                final String getQuery = "SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)"; 
                final Query query = getSession().createQuery(getQuery); 
                final int rowCount = query.executeUpdate(); // check that the rowCount is 1 
                log.debug("get successful"); 
//             return what??
            } catch (RuntimeException re) { 
                log.error("get not successful", re); 
                throw re; 
            } 
    }
A: 

SELECT * FROM Users WHERE Id = (SELECT MIN(Id) FROM Users)

:)

Snake
@Snake , ok the query how do I implement it? I'll update my question
London
+2  A: 

You can

  • use:

    Query query = session.createQuery("from User");
    query.setMaxResults(1);
    User result = (User) query.uniqueResult();
    
  • use User user = session.get(User.class, id); if you know the ID upfront.

Bozho
I'm sorry but I have to downvote this answer: 1. `uniqueResult()` will throw an exception if the query returns more than one result (which is very likely the case of `from User`) 2. Don't retrieve all Users if want only one of them (what if there are 10⁶ users in the table?) 3. Don't use `LIMIT` which is not portable, use `setMaxResults()` and let Hibernate do its job.
Pascal Thivent
thanks, updated. (6-hour meetings do bad things to people :) )
Bozho
No problem :) Downvote removed.
Pascal Thivent
A: 

Don't remember exactly but i think there is a method getSingleResult in JPA and also in Hibernate so...

But this method perhaps throw exception when multiple results are returned... can't remember...

Actually there is also getResultList returning a List of entities, and you could do list.get(0) no?

Or create a query with LIMIT 1?

Sebastien Lorber
A: 

In MS SQL Server we do it like,

First user, min ID,

SELECT TOP 1 * FROM Users ORDER BY Id

Latest user, max ID,

SELECT TOP 1 * FROM Users ORDER BY Id DESC

thanks.

Paarth
yup.. this'll work in sybase as well. in oracle it'd be Select * from Users where rownum = 1
Nico
+2  A: 

Get all users ordered by id and limit the results to 1 (but don't use LIMIT, use setMaxResults() to remain portable):

Query q = session.createQuery("from User u order by u.id");
q.setMaxResults(1);
User u = (User) q.uniqueResult();
Pascal Thivent