Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA find the Last entry

Tags:

java

sql

jpa

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 ;)

like image 578
Roch Avatar asked Jan 13 '10 23:01

Roch


3 Answers

The results of query methods can be limited via the keywords first or top, which can be used interchangeably. An optional numeric value can be appended to top/first to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed.

JpaClass findFirstByOrderByIdDesc();

referenced by Spring Data JPA docs

like image 184
arnoe Avatar answered Nov 16 '22 16:11

arnoe


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.

query.setMaxResults(1).getResultList();
like image 24
rayd09 Avatar answered Nov 16 '22 17:11

rayd09


I know I'm late to the party, but this might help someone. If you want to fetch the latest entry by created timestamp. (When you don't want to rely on the table id):

YourEntity findFirstByOrderByCreatedTsByDesc();

like image 6
SkyHigh Avatar answered Nov 16 '22 15:11

SkyHigh