使用max,min,group by和order by将TypedQuery转换为criteriaQuery(JPA 2.0)

时间:2011-10-04 11:37:46

标签: java group-by jpa-2.0 criteria-api


我在将一个运行良好的typedQuery转换为纯JPA 2.0 criteriaQuery:/

时遇到了一些困难

关注我的工作类型:

String name = "Station1";

Query qry = em.createQuery("
select YEAR(s.fetchDate), MAX(s.actExport)-MIN(s.actExport), MIN(s.actExport), MAX(s.actExport) 
from StationItem s 
where s.fetchDate >= '2008' and s.fetchDate < '2012' 
    and s.errorState=0
    and s.actExport>0
    and s.name = :name        
group by YEAR(s.fetchDate)
order by s.fetchDate ");

qry.setParameter("name", name);

现在我的主要问题是按年份(日期)分组[日期的格式为YYYY-MM-DD hh:MM]并写入最大和最小表达式。
我开始是这样的:

Date endTime = new Date();
Date startTime = DateUtil.yearsInPast(5,endTime); //own helper class

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Tuple> cq = cb.createTupleQuery();
Root<StationItem> r = cq.from(StationItem.class);

// setting predicates (used in where clause)
Predicate pStation = cb.equal(r.get("name"), station);
Predicate pError = cb.equal(r.get("errorState"), 0);
Predicate pTime = cb.between(r.get("fetchDate").as(Date.class), startTime, endTime);
Predicate pNotNull = cb.notEqual(r.get(selection), 0);

// setting expressions (used in select clause)
Expression<Number> select = r.get(selection);
Expression<Number> maximum = cb.max(select);
Expression<Number> minimum = cb.min(select);
Expression<Date> fetchDate = r.get("fetchDate").as(Date.class);

// building my query (select, where, group by, order by)
cq.multiselect(fetchDate, select, maximum, minimum); //fetchDate needs to be shrinked to only the Year! and Max-Min would be nice (but this can be done when writing the data to an object/list)
cq.where(pStation, pTime, pError, pNotNull);
cq.groupBy(fetchDate); //grouping should be done by the year of the fetchDate
cq.orderBy(cb.asc(fetchDate));

// write results to a list
List<Tuple> l = em.createQuery(cq).getResultList();

目前值Max和Min是相同的...但这是非常合乎逻辑的,因为没有为fetchDate按年份分组... 如何才能在我的约会年份实现分组,最大最小计算结果如何?

提前谢谢你 罗恩。

1 个答案:

答案 0 :(得分:4)

您可以使用Criteria api调用基础dbms上的函数,例如YEAR或MONTH。这是一个例子:

builder.function("YEAR", Integer.class, r.get("fetchDate"))