Get record with max id, using Hibernate Criteria

后端 未结 8 1696
后悔当初
后悔当初 2020-12-15 16:18

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

8条回答
  •  时光取名叫无心
    2020-12-15 17:05

    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.

提交回复
热议问题