【发布时间】:2020-10-23 01:26:55
【问题描述】:
我正在尝试将 SQL 查询更改为 CriteriaBuilder 方式并遇到此错误。
Caused by: org.postgresql.util.PSQLException:
ERROR: column "lopcoverag0_.slot" must appear in the GROUP BY clause
or be used in an aggregate function
SQL - 当我在 SQLWorkbench 中执行此查询时,此查询对我有效
select count(*) from (Select distinct slot from lop_coverage
where pageFamily='Gateway' and currentStatus ='Active'
and (lop in ("[en_US]","none")) group by creativeID) as totalcount;
致JPA CriteriaBuilder:
CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class);
Root<LOPCoverage> root = criteriaQuery.from(LOPCoverage.class);
criteriaQuery.select(root.get(LOPCoverage_.slot)).distinct(true);
List<String> lopList = Arrays.asList(new String[]{"none", "[en_US]"});
Expression<String> lopExpression = root.get(LOPCoverage_.lop);
Predicate lopINPredicate = lopExpression.in(lopList);
Predicate andRestriction = criteriaBuilder.and(
criteriaBuilder.equal(root.get("pageFamily"), pageFamily),
lopINPredicate);
criteriaQuery.where(andRestriction).groupBy(root.get("creativeID"));
System.out.println( session.createQuery(criteriaQuery).list());
这是从休眠日志生成的查询
Hibernate: select distinct lopcoverag0_.slot as col_0_0_ from
lop_coverage lopcoverag0_ where lopcoverag0_.page_family=? and
(lopcoverag0_.lop in (? , ?)) group by lopcoverag0_.creative_id
我知道我在 criteriaBuilder 中的代码有错误,有人可以告诉我问题或将我指向正确的位置
【问题讨论】:
-
除非 creativeID 是主键,否则您显示的第一个查询也不起作用。由于您现在正在查询具有不同列的不同表,因此它可能不再是主键。
-
是的。表不同。最初,包中的代码是使用 JDBC 和纯 SQL 字符串编写的,DB 是 mysql。现在我正在重构整个代码以使用 hibernate 和 postgresql。
-
@jjanes 我更新了查询。请检查
标签: java postgresql hibernate criteria hibernate-criteria