Hibernate条件限制: - 如何获取当前和上个月的数据

时间:2016-03-31 07:48:51

标签: java mysql hibernate criteria restrictions

以下是从创建日期获取特定月份和年份数据的方法。

    @Override
    public List getMonthlyOrdersSummary(LabOrderConditions labOrderConditions) {
        Criteria criteria = getCurrentSession().createCriteria(LabOrder.class);

        criteria.add(Restrictions.gt("orderNo", 0));
        if (StringUtils.isNotBlank(labOrderConditions.getClientCode()))
            criteria.add(Restrictions.eq("clientCode", labOrderConditions.getClientCode()));

        if (labOrderConditions.getAccountCodesList() != null) {
            criteria.add(Restrictions.in("practice.code", labOrderConditions.getAccountCodesList()));
        }


        if (StringUtils.isNotBlank(labOrderConditions.getClientsCodes())) {
            if (labOrderConditions.getCallingPlace().equalsIgnoreCase("allClients")) {
                List<String> items = Arrays.asList(labOrderConditions.getClientsCodes().split("\\s*,\\s*"));
                criteria.add(Restrictions.in("clientCode", items));
            }
        }

        criteria.add(Restrictions.sqlRestriction("YEAR(createdDate)=" + labOrderConditions.getYear()));
        ProjectionList projectionList = Projections.projectionList();

        if (labOrderConditions.getCallingPlace().equalsIgnoreCase("allClients")) {
            projectionList.add(Projections.groupProperty("clientCode"), "clientCode");
        }

        projectionList.add(Projections.sqlGroupProjection("MONTHNAME(createdDate) as orderMonthName", "MONTHNAME(createdDate)",
                new String[] { "orderMonthName" }, new Type[] { StandardBasicTypes.STRING }));
        projectionList.add(Projections.sqlGroupProjection("Month(createdDate) as orderMonthNo", "Month(createdDate)", new String[] { "orderMonthNo" },
                new Type[] { StandardBasicTypes.INTEGER }));

        projectionList.add(Projections.rowCount());
        criteria.setProjection(projectionList);
        criteria.addOrder(org.hibernate.criterion.Order.asc("createdDate"));
        return criteria.list();
    }

那么如何写当前和上个月的限制。

我只想要像criteria.add(Restrictions.in("MONTHNAME(createdDate)", labOrderConditions.getCompareMonthList()));

这样的东西

如果有人有任何建议与我分享。

由于 Sitansu

1 个答案:

答案 0 :(得分:1)

在labOrderConditions.getCompareMonthList()中,用Java创建相应的开始和结束Date对象,然后:

criteria.add(Restrictions.between("createdDate", startDate, endDate));

如果您有多个间隔,您还可以添加“或”限制。

这会解决您的问题,还是您期望得到其他结果?