Spring / Hibernate:JPA异常:: JOIN期望的路径

时间:2016-11-02 21:40:31

标签: java spring hibernate spring-mvc jpa

尝试运行此查询时获取QuerySyntaxException:

BC
+-----+----+-------+----+
|group|  id|group_A|id_A|
+-----+----+-------+----+
|    0| 103|   null|null|
|    1| 106|   null|null|
|    0| 100|   null|null|
|    1|1007|   null|null|
+-----+----+-------+----+

产生此错误:

public interface SignalRepository extends PagingAndSortingRepository<Signal, Long> {

...
@Query("select p1 from Signal p1 LEFT JOIN Signal p2 " 
        + " ON (p1.zoneId = p2.zoneId AND p1.createdAt < p2.createdAt) "
        + " where p2.id is null AND p1.userId=?#{[0]} AND p1.pid=?#{[1]}")

此查询在键入的SQL命令行(和caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [select p1 from com.newco.models.Signal p1 LEFT JOIN Signal p2 ON (p1.zoneId = p2.zoneId AND p1.createdAt < p2.createdAt) where p2.id is null AND p1.userId=?1 AND p1.pid=?2] at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:91) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:268) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final] )时运行良好,但在Spring / JAP中失败。

1 个答案:

答案 0 :(得分:1)

  

加入的预期路径!

使用JPQL,您不能像在SQL中那样编写JOIN。您必须精确连接关系的路径


您可以执行本机SQL查询:

VECT1         (x) : ORIGIN = 0xFF90, LENGTH = 0x0002

您可以在JPQL查询中调整SQL查询 要做到这一点,你应该改变几件事。

1)我不确定JPA是否识别此语法:Query q = em.createNativeQuery("YourQuery", Signal.class); 来设置参数值。您应该使用:p1.userId=?#{[0]} AND p1.pid=?#{[1]}

2)承认你在p1.userId=:?1 and p1.pid=:?2实体中声明一个自反关系(p2),Signal条件应该是这样的(LEFT JOIN是在实体关系和{{1}变成JOIN):

ON

3)如果WITH实体具有基于此条件的自反关系,则"select p1 FROM Signal p1 LEFT JOIN p1.p2 p2 " + " WITH p1.createdAt < p2.createdAt " + " where p2.id is null AND p1.userId=:?1 AND p1.pid=:?2 中不需要p1.zoneId = p2.zoneId条件。