gpt4 book ai didi

java - 将 TypedQuery 转换为具有最大、最小、分组依据和排序依据的 criteriaQuery (JPA 2.0)

转载 作者:行者123 更新时间:2023-11-30 07:30:50 25 4
gpt4 key购买 nike


我在将工作良好的 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);

现在我的主要问题是按 Year(date) [date 的格式为 YYYY-MM-DD hh:MM] 分组并编写 Max 和 Min 表达式。
我是这样开始的:

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 没有按年份分组...我如何才能仅按日期的年份进行分组,最大-最小计算结果如何?

提前致谢
罗恩。

最佳答案

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

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

关于java - 将 TypedQuery 转换为具有最大、最小、分组依据和排序依据的 criteriaQuery (JPA 2.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7647276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com