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?
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.
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 .
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With