从SQL到JPQL的加入请求

时间:2018-10-25 12:31:06

标签: sql jpa join jpql

希望这里有人可以帮助我。

我已找到要在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;

仅在列表中保留最接近的日期,每个ID仅保留一个日期(在我的示例中为324和326):

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

我试图翻译成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();

然后出现以下错误:“联接关联路径不是有效的表达式。”

有人知道如何解决此问题吗?

2 个答案:

答案 0 :(得分:0)

根据this answer,不可能在join子句中使用子查询。 关于Criteria APIHQL

也可以这样说

也许您可以使用HAVING子句或将子查询移至WHERE子句来重写查询?

答案 1 :(得分:0)

我通过删除Join子句使它起作用。

像这样:

 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 ";

希望这对某人有帮助。