Sql to hibernate(带分组的嵌套查询)

时间:2017-10-05 11:30:16

标签: mysql hibernate hibernate-criteria

我正在尝试将我的sql查询转换为hibernate查询

 select * from user_projects where endDate is not null and startDate is not null and soft_delete=? and startDate<=? and 
endDate>=? and endDate<=? and (endDate,user_id) in (select MAX(endDate),user_id from user_projects  
where soft_delete=? group by user_id) ;

我把它转换成了hibernate代码。 这是我的hibernate代码

        List<Staffing> staffing = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy MM dd");
        String dateString = df.format(duration);
            Date date = df.parse(dateString);

        DetachedCriteria maxDate=DetachedCriteria.forClass(Staffing.class);
        maxDate.setProjection(Projections.projectionList().add(Projections.groupProperty("user")).add(Projections.max("endDate"),"maxDate"));
        Criteria criteria = getCriteria();

        criteria.add(Restrictions.isNotNull("startDate")).add(Restrictions.le("startDate", new Date()));
        criteria.add(Restrictions.isNotNull("endDate")).add(Restrictions.ge("endDate", new Date()));
        criteria.add(Restrictions.eq("softDelete", false));

        criteria.add(Subqueries.le(date, maxDate));
        staffing = criteria.list();
        return staffing;

但是我得到了对象数组列表。任何人都可以帮我正确转换它。

1 个答案:

答案 0 :(得分:0)

你好你可以尝试使用像这样的结果变换器

criteria.setResultTransformer(Transformers.aliasToBean(user_projects.class));

但是从sql查询返回的属性的名称必须与user_projects.class中的属性名称相同