SQL to JPQL join request

眉间皱痕 提交于 2019-12-11 06:56:23

问题


Hopefully someone here can help me.

I have found the request I want to use on sqlDev :

SELECT t1.*
  FROM table1 t1 INNER JOIN
(
  SELECT ev.ID_AGENCE, MAX(ev.DATE_CREATION) DATE_CREATION
    FROM table1 ev
    WHERE ev.ID_AGENCE IN (326,324)
    GROUP BY ev.ID_AGENCE
) t2 ON t1.ID_AGENCE = t2.ID_AGENCE
    AND t1.DATE_CREATION = t2.DATE_CREATION
    order by t1.id_agence;

to keep only the closest date in a list, and only one per id (324 and 326 here in my exemple) :

324 22/10/18
324 21/10/18
324 20/10/18
326 10/08/18
326 09/08/18
326 07/08/18
326 06/08/18
326 05/08/18
326 04/08/18
326 03/08/18
326 02/08/18
326 01/08/18

I tried to translate to JPA (JPQL) :

final String requete = "SELECT e FROM ClasseJava JOIN " + 
                "( " + 
                    "SELECT f.id, MAX(f.dateCreation) dateCreation " + 
                    "FROM ClasseJava f " + 
                    "WHERE f.idAgence IN (326,324) " + 
                    "GROUP BY f.idAgence " + 
                ") "                        + 
                "t ON e.idAgence = t.idAgence " + 
                "AND e.dateCreation = t.dateCreation " + 
                "GROUP BY idAgence ";

final TypedQuery<ClasseJava> query = entityManager.createQuery(requete, ClasseJava.class);
query.setParameter("listIdAgence", listIdAgence);
return query.getResultList();

And I get the following error : "The join association path is not a valid expression."

Does anyone have an idea on how to fix the issue ?


回答1:


According to this answer it's impossible to use a subquery in a join clause. Same can be said about Criteria API and HQL

Maybe you can rewrite your query using a HAVING clause or by moving the subquery to a WHERE clause?




回答2:


I made it work by removing the Join clause.

like this :

 final String requete = "SELECT e FROM classeJava e, " + 
"( " + 
"SELECT f.idAgence, MAX(f.dateCreation) dateCreation " + 
"FROM classeJava f " + 
"WHERE f.idAgence IN :listIdAgence " + 
"GROUP BY f.idAgence " + 
") " + 
"t WHERE e.idAgence = t.idAgence " + 
"AND e.dateCreation = t.dateCreation " + 
"ORDER BY e.idAgence ";

Hope this helps someone.



来源:https://stackoverflow.com/questions/52989338/sql-to-jpql-join-request

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!