我有以下JPA实体(省略了getters,setter和不相关的字段):
@Entity
@Table(name = "transaction")
public class Transaction {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@Column(name = "start_date", nullable = false)
private Date startDate;
}
我的目标是使用JPQL或条件API实施查询,该查询将返回每天平均交易量和每天最大交易量。
提供所需结果的本地SQL查询(MySQL数据库)如下:
select max(cnt) from (
select date(start_date) start_date, count(t.id) cnt
from transaction t
group by date(t.start_date)
) t;
select avg(cnt) from (
select date(start_date) start_date, count(t.id) cnt
from transaction t
group by date(t.start_date)
) t;
不幸的是,不鼓励使用本机SQL查询,并且JPQL不允许在where子句中使用子查询。
谢谢。
添加:
我从以下Spring Data查询开始:
@Query("select max(cnt) from ("
+ "select date(t.startDate) startDate, count(t.id) cnt "
+ "from Transaction t "
+ "group by date(t.startDate))")
但是它显然不起作用:
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 22 [select max(cnt) from (select date(t.startDate) startDate, count(t.id) cnt from Transaction t group by date(startDate))]
我可以想象,使用排序和限制输出可以管理对max的搜索,但这对平均无济于事。
答案 0 :(得分:0)
有两种原因导致无法在JPQL(或标准)中编写所需的内容:
对于此查询,您可能只询问可移植性(尽可能将本机SQL保留为标准)。
一种选择是使用FluentJPA,它消除了嵌入式字符串,并与Java和JPA紧密集成。因此查询将如下所示:
public int getAvgCount() {
FluentQuery query = FluentJPA.SQL(() -> {
DailyCount daily = subQuery((Transaction t) -> {
Date date = alias(DATE(t.getStartDate()), DailyCount::getDate);
int count = alias(COUNT(t.getId()), DailyCount::getCount);
SELECT(date, count);
FROM(t);
GROUP(BY(date));
});
SELECT(AVG(daily.getCount())); // or MAX
FROM(daily);
});
return query.createQuery(em, Integer.class).getSingleResult();
}
类型声明:
@Tuple
@Getter // lombok
public class DailyCount {
private Integer count;
private Date date;
}
产生的SQL:
SELECT AVG(q0.count)
FROM (SELECT DATE(t0.start_date) AS date, COUNT(t0.id) AS count
FROM transaction t0
GROUP BY DATE(t0.start_date)) q0