JPA / JPQL COUNT question

I have the following JPQL query -

SELECT f.md5 
FROM File f, Collection leafCollections, Collection instCollections 
WHERE (f.status = com.foo.bar.FileStatus.Happy OR f.status = com.foo.bar.FileStatus.Sad) 
      AND f.collectionId = leafCollections.collectionId 
      AND leafCollections.instanceCollectionId = instCollections.collectionId 
GROUP BY f.md5, instCollections.collectionId 

It basically returns md5s for files that are organized in a tree hierarchy, so if the same MD5 appears on more than one sheet in a particular branch of the hierarchy, it will be shown only once (thanks to GROUP BY).

It works great. Say I get 100 lines back. Each line contains md5 as a line.

Now I want to get COUNT of returned rows. I thought I could just do:

SELECT COUNT(f.md5) 
FROM File f, Collection leafCollections, Collection instCollections 
WHERE (f.status = com.foo.bar.FileStatus.Happy OR f.status = com.foo.bar.FileStatus.Sad) 
      AND f.collectionId = leafCollections.collectionId 
      AND leafCollections.instanceCollectionId = instCollections.collectionId 
GROUP BY f.md5, instCollections.collectionId 

However, this returns 100 lines, each containing a long one, representing the number of times md5 appeared in the branch. I just wanted to get 1 row back with a long value of 100, which is the total number of rows returned by the original request. I feel like I'm missing something obvious.

?

+3
1

@doc_180. getSingleResult()

, .

// Assuming that the Query is strQ
Query q = entityManager.createQuery( strQ );
int count = ( (Integer) q.getSingleResult() ).intValue();
+6

Source: https://habr.com/ru/post/1787097/


All Articles