Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get record with max id, using Hibernate Criteria

Using Hibernate's Criteria API, I want to select the record within a table with the maximum value for a given column.

I tried to use Projections, creating an alias for max(colunName), then using it in restrictions.eq(), but it keeps telling me "invalid number".

What's the correct way to do that with Hibernate?

like image 867
Amr Faisal Avatar asked Oct 10 '10 11:10

Amr Faisal


People also ask

How can we get data from Criteria in hibernate?

Hibernate in Practice - The Complete Course Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.

How can we get unique result in hibernate criteria?

Fetch a Single Result If you want to obtain a single Object reference instead of a List, the uniqueResult() method on the Criteria object returns an object or null. If there is more than one result, the uniqueResult() method throws a HibernateException .

How subquery is used in hibernate criteria?

I first set the Book entity as the root and join it with the Author entity. Then I use the count function to determine the number of Books in the SELECT clause. And after that, I compare the id of the Author entity which got selected in the outer query with the id of the Author selected in the subquery.


2 Answers

You can use a DetachedCriteria to express a subquery, something like this:

DetachedCriteria maxId = DetachedCriteria.forClass(Foo.class)     .setProjection( Projections.max("id") ); session.createCriteria(Foo.class)     .add( Property.forName("id").eq(maxId) )     .list(); 

References

  • Hibernate Core Reference Guide
    • 15.8. Detached queries and subqueries
like image 71
Pascal Thivent Avatar answered Oct 14 '22 00:10

Pascal Thivent


I found that using addOrder and setMaxResults together worked for me.

Criteria c = session.createCriteria(Thingy.class); c.addOrder(Order.desc("id")); c.setMaxResults(1); return (Thingy)c.uniqueResult(); 

Using the MySQL dialect, this generates a SQL prepared statement about like this (snipping out some of the fields):

select this_.id ... from Thingy this_ order by this_.id desc limit ? 

I am not sure if this solution would be effective for dialects other than MySQL.

like image 34
amacleod Avatar answered Oct 14 '22 01:10

amacleod