Get record with max id, using Hibernate Criteria

后端 未结 8 1695
后悔当初
后悔当初 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条回答
  •  -上瘾入骨i
    2020-12-15 16:57

        Date maxDateFromDB = null;
        Session session = (Session) entityManager.getDelegate();
    //Register is and Entity and assume maxDateFromDB is a column.
    //Status is another entity with Enum Applied.
    //Code is the Parameter for One to One Relation between Register and Profile entity.
        Criteria criteria = session.createCriteria(Register.class).setProjection(Projections.max("maxDateFromDB") )
        .add(Restrictions.eq("status.id", Status.Name.APPLIED.instance().getId()));
        if(code != null && code > 0) {
            criteria.add(Restrictions.eq("profile.id", code));
        }
        List list = criteria.list();
    
        if(!CollectionUtils.isEmpty(list)){
            maxDateFromDB = list.get(0);
        }
    

提交回复
热议问题