How to get jpql query from sql query?

2019-08-02 23:40发布

i can make sql simple query in JPQL like this and its work well :

Query query = em.createQuery("SELECT p2 FROM Zp01 p2 where p2.gestionnaire IN (SELECT d.libelle FROM Affaire d)") ;
liszp01general= (List<Zp01>) query.getResultList();

but i cant translate this query to JPQL thats already working in sql :

SELECT p2.* from zp01 p2 join (SELECT TYPEC,count(TYPEC) as cnt_typec FROM planning_cuisson group by TYPEC HAVING COUNT(TYPEC) > 0) p1 where p2.type_cuisson=p1.typec order by cnt_typec asc ;

i tried this but didnt work :

Query query = em.createQuery("SELECT p2 FROM Zp01 p2 join ( select G.TYPEC,count(G.TYPEC) as cnt_typec from PlanningCuisson G group by G.TYPEC HAVING COUNT(G.TYPEC) > 0) p1 Where p2.typeCuisson=p1.typec and p2.ordre NOT IN (SELECT k.numof FROM OfSemiplanifie k) AND p2.gestionnaire IN (SELECT d.libelle FROM Affaire d) order by cnt_typec asc");
      liszp01general= (List<Zp01>) query.getResultList();

标签: mysql sql jpa jpql
1条回答
乱世女痞
2楼-- · 2019-08-03 00:00

This is an older post, but in case it helps anyone else out, I'll just add that the current version of JPQL doesn't support sub-queries in the FROM clause. From the JPQL Reference:

Subqueries are restricted to the WHERE and HAVING clauses in this release. Support for subqueries in the FROM clause will be considered in a later release of the specification.

When I had to do something similar on a project, I had to move the aggregate sub-query down into the where clause, add a Comparator to the entity, and then do a Collections.sort after the JPQL call. So the query would become something along the lines of:

...
WHERE p2.typeCuisson IN (SELECT G.TYPEC 
FROM PlanningCuisson G 
GROUP BY G.TYPEC 
HAVING COUNT(G.TYPEC) > 0)...

With a Collections.sort after the query.getResultList()

查看更多
登录 后发表回答