开发者

How to get the most recently added row from a certain table

开发者 https://www.devze.com 2023-01-17 12:56 出处:网络
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 ar

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 f开发者_JAVA技巧indOne from the list. I would prefer not to paginate by setting the rowsPerPage as 1 and then fetch the resultSet.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消