tags:

views:

49

answers:

1

Hi, I would like to know what's the best way to get the last entry of a table with JPA. In Sql, what I'm looking for would be like:

 select id from table order by id desc limit 1 

I was thinking about model.count() but that sounds more like a hack than a good solution ;)

+1  A: 

You could use a JPQL query that looks very similar to your query.

select t from JpaClass t order by t.id desc

After you establish your Query object you could then call query.getSingleResult() or call query.setMaxResults(1) followed by query.getResultList()

EDIT: My mistake: Please note mtpettyp's comment below.
Don't use query.getSingleResult() as an exception could be thrown if there is not exactly one row returned - see java.sun.com/javaee/5/…() - mtpettyp
Go with setMaxResults and getResultList.

rayd09
Don't use query.getSingleResult() as an exception could be thrown if there is not exactly one row returned - see http://java.sun.com/javaee/5/docs/api/javax/persistence/Query.html#getSingleResult()
mtpettyp