是否可以将COUNT与DISTINCT JPA投影一起使用?

Dav*_*ker 13 java jpa

我正在使用JPA distinct投影来获取一些数据:

select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...
Run Code Online (Sandbox Code Playgroud)

这适用于setFirstResult和setMaxResults到页面数据.

但是,我需要计算总行数而不提取所有行.我试过了:

select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...
Run Code Online (Sandbox Code Playgroud)

这不起作用(无论如何都使用EclipseLink)并且JPA规范似乎不允许这样做.还有另外一种方法吗?我不想编写SQL查询来执行此操作.

Lar*_*ahl 12

试试这个:

select count(distinct o) from SomeEntity o where ...
Run Code Online (Sandbox Code Playgroud)

  • 只是要小心不要使用 count(distinct(o)) - 额外的括号是一个错误 (3认同)

She*_*ari -5

您说您不想编写 SQL 查询来执行此操作,但是 JPA QL 和 SQL 之间有什么区别?如果您不想使用该getResultList().size()方法来确定总行数,那么唯一的方法是使用本机 sql 查询。

entityManager.createNativeQuery("select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...").getSingleResult();
Run Code Online (Sandbox Code Playgroud)

或者

entityManager.createQuery("select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...").getResultList().size();
Run Code Online (Sandbox Code Playgroud)