开发者

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

开发者 https://www.devze.com 2023-01-18 22:43 出处:网络
I am using a JPA distinct projection to get s开发者_运维百科ome data: select distinct o.f1, o.f2, o.f3 from SomeEntity o where ...

I am using a JPA distinct projection to get s开发者_运维百科ome data:

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

This works fine with setFirstResult and setMaxResults to page data.

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. Is there another way? I don't want to have to write an SQL query to do this.


Try this:

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


If EclipseLink and your underlying DB allow subselects try:

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.

This works for hibernate sql named queries. I'll try it on JP-QL queries soon.


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....)

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? 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.

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消