JPA find the Last entry

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


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

select t from JpaClass t order by desc

After you establish your Query object you could then call

query.getSingleResult() or call query.setMaxResults(1)

followed by


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…() - mtpettyp

Go with setMaxResults and getResultList.


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

Need Your Help

Importing data into R from google spreadsheet

r google-sheets

There seems to be a change in the google spreadsheet publishing options. It is no longer possible to publish to the web as csv or tab file (see this recent post). Thus the usual way to use RCurl to

Simulate a faulty block device with read errors?

linux device device-emulation

I'm looking for an easier way to test my application against faulty block devices that generate i/o read errors when certain blocks are read. Trying to use a physical hard drive with known bad blo...