tags:

views:

35

answers:

2

How to get the most recently added row from a certain table, which satisfies a certain condition.

If I use javax/persistence/Query.html#getSingleResult() we get a NonUniqueResultException if there are multiple rows satisifying the query. I need the equivalent of findOne from the list. I would prefer not to paginate by setting the rowsPerPage as 1 and then fetch the resultSet.

A: 

jpa, and hibernate, require that every row must have unique id. So choose a row with id=max(id). this will work in most cases where id generation is incremental. Not sure how to get it, if id is a string, for example.

foret
this is dependent on the id generation strategy, I am a little hesitant to use this technique
Samuel
+2  A: 

You indicated that you don't want to use "rowsPerPage", but this is a proper way to do it:

query.setMaxResults(1)

However, that does not guarantee that the row is the most recent, unless you query for a criteria including a date. If you don't have such column, and you are not using auto-increment (which should be a last resort), you can't achieve your goal.

Bozho