简体   繁体   English

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

[英]Is it possible to use COUNT with a DISTINCT JPA projection?

I am using a JPA distinct projection to get some data:我正在使用 JPA 不同投影来获取一些数据:

select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...

This works fine with setFirstResult and setMaxResults to page data.这适用于 setFirstResult 和 setMaxResults 页面数据。

However I need to count the total number of rows without fetching all of them.但是我需要计算总行数而不提取所有行数。 I have tried:我试过:

select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...

This does not work (with EclipseLink anyway) and it doesn't seem to be allowed by the JPA spec.这不起作用(无论如何使用 EclipseLink)并且 JPA 规范似乎不允许这样做。 Is there another way?还有其他方法吗? I don't want to have to write an SQL query to do this.我不想编写 SQL 查询来执行此操作。

试试这个:

select count(distinct o) from SomeEntity o where ...

If EclipseLink and your underlying DB allow subselects try:如果 EclipseLink 和您的底层数据库允许子选择,请尝试:

select count(*) from (select distinct o.f1, o.f2, o.f3 from SomeEntity o where ... )

That way your can just put your JQL in to count its total result size.这样您就可以将 JQL 放入计算其总结果大小。

This works for hibernate sql named queries.这适用于 hibernate sql 命名查询。 I'll try it on JP-QL queries soon.我很快就会在 JP-QL 查询上试用它。

Though this answer is coming late but it might help future people.虽然这个答案来晚了,但它可能会帮助未来的人。 In your repository.在您的存储库中。 This worked for me in my own case.这在我自己的情况下对我有用。

@Query("SELECT DISTINCT COUNT(o.f1, o.f2...) FROM SomeEntity o WHERE....) @Query("SELECT DISTINCT COUNT(o.f1, o.f2...) FROM SomeEntity o WHERE....)

Hope it helps others.希望它可以帮助其他人。

You say you don't want to write an SQL query to do this, but what is the difference between JPA QL and SQL?您说您不想编写 SQL 查询来执行此操作,但是 JPA QL 和 SQL 之间有什么区别? If you don't want to use the getResultList().size() method to determine the number of total rows, then the only way is to use a native sql query.如果不想使用getResultList().size()方法来确定总行数,那么唯一的方法就是使用原生 sql 查询。

entityManager.createNativeQuery("select count(distinct o.f1, o.f2, o.f3) from SomeEntity o where ...").getSingleResult();

or

entityManager.createQuery("select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...").getResultList().size();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM