Hibernate Criteria - 如果MAX为null,则返回null,否则返回Max Value-CASE WHEN

时间:2017-10-13 08:23:14

标签: mysql hibernate criteria detachedcriteria

我有一个SQL查询

    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标准就像

DetachedCriteria maxDate=DetachedCriteria.forClass(Staffing.class);
        maxDate.add(Restrictions.eq("softDelete", false));
        maxDate.setProjection(Projections.projectionList().add(Projections.groupProperty("user").as("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())).add(Restrictions.le("endDate", date));
        criteria.add(Restrictions.eq("softDelete", false));
        criteria.add(Subqueries.propertiesIn(new String[]{"user","endDate"}, maxDate));
        staffing = criteria.list();

现在我已将查询更新为

select * from user_projects where endDate is not null and startDate is not null and soft_delete=? and startDate<=? and 
    endDate>=? and endDate<=? and (user_id,endDate) in (select user_id ,
    CASE WHEN MAX(CASE WHEN enddate IS NULL THEN 1 ELSE 0 END) = 0
            THEN MAX(enddate)
       END
    from user_projects where soft_delete=0 group by user_id)

现在我被困在这个案例中。任何建议如何修改我的更新sql的hibernate标准。我已经读过hibernate不支持CASE WHEN那么有没有其他方法来解决这个问题。提前致谢 !!!

0 个答案:

没有答案