Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA - MAX of COUNT or SELECT FROM SELECT

I wrote the following query for MySQL:

SELECT subquery.t1_column1, 
    subquery.t2_id, 
    MAX(subquery.val)
FROM (
    SELECT t1.column1 as t1_column1, 
        t1.id_t2 AS t2_id,
        count(1) AS val
    FROM table1 t1
    INNER JOIN table2 t2
    ON t2.id = t1.id_t2
    GROUP BY t1.id_t2
) subquery
GROUP BY t1_column1

And I'd like to translate it into JPA (JPQL or criteria query).

I don't know how to make this max(count) thing, and JPA doesn't seem to like the SELECT FROM SELECT...

If anyone has an idea other than native queries (I'll do it for now), it would be great.

like image 419
Bob Avatar asked May 22 '12 09:05

Bob


1 Answers

I haven't checked tha JPA specification, but given that the Hibernate documentation says

Note that HQL subqueries can occur only in the select or where clauses.

I very much doubt that your query can be transformed in a valid JPQL query.

You'll have to keep using this native SQL query.

like image 91
JB Nizet Avatar answered Nov 15 '22 08:11

JB Nizet