Get record with max id, using Hibernate Criteria

后端 未结 8 1659
后悔当初
后悔当初 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:16

    The cleaner solution would also be :

    DetachedCriteria criteria = DetachedCriteria.forClass(Foo.class).setProjection(Projections.max("id"));
    Foo fooObj =(Foo) criteria.getExecutableCriteria(getCurrentSession()).list().get(0);
    
    0 讨论(0)
  • 2020-12-15 17:20

    To do it entirely with Detached Criteria (because I like to construct the detached criteria without a session)

    DetachedCriteria maxQuery = DetachedCriteria.forClass(Foo.class)
        .setProjection( Projections.max("id") );
    DetachedCriteria recordQuery = DetachedCriteria.forClass(Foo.class)
        .add(Property.forName("id").eq(maxId) );
    
    0 讨论(0)
提交回复
热议问题