【问题标题】:Complex JPQL Query Returning 0 Zero Results Fetching Table Twice in Query复杂的 JPQL 查询返回 0 个零结果在查询中两次获取表
【发布时间】:2019-02-17 07:02:57
【问题描述】:

我正在开发一个应用程序,在该应用程序中,公交车司机可以与孩子的父母在他们处理的路线上进行群聊。

我希望有一个选项可以在公交车到达的最后一站之前向所有聊天室发送消息。

我试过这个查询,但它总是返回 0 个结果。什么时候肯定应该返回至少一个。

1 | @Query("select g from GroupChat g " + 
2 |        "join g.route r " +
3 |        "join r.bus b " +
4 |        "join b.mostRecentStop mrs " +
5 |        "join r.stops s " +
6 |        "join s.children c " +
7 |        "where r.routeId = :routeId " +
8 |        "and s.stopTime <= mrs.stopTime " +
9 |        "and g.childId = c.childId ")
10|Set<GroupChat> getAllGroupChatsOnRouteForPreviousStops(@Param("routeId") short routeId);

GroupChats PK 是 routeId-childId

第 2 行获取与群聊关联的路由。
3 号线为该路线取车。
4 号线获取公交车最近到达的站点。
5 号线获取路线上的所有站点
第 6 行获取路线上的所有孩子(即每个站点的每个孩子)
第 7 行仅过滤查询的路由。
第 8 行过滤最近停靠点之前的停靠点
第 9 行仅筛选剩余站点上仅儿童的群聊。

我做错了什么?

【问题讨论】:

  • 在 application.properties 中添加 spring.jpa.show-sql = true。现在,执行这个查询。您现在将能够在应用程序记录器中进行 SQL 查询。转到 SQL 终端并通过将 ? 替换为 routeId 值来执行相同的操作。从那里开始逐行调试查询。
  • @MaruthiAdithya 所以我已经尝试过了,奇怪的是我在 mysql 工作台上运行查询的结果与我的应用程序不同。
  • 那么,你在 mysql workbench 中得到超过 0 个结果吗?
  • @MaruthiAdithya 我得到了我期待的一排
  • 太棒了。所以,你的查询是完美的。尝试将Set&lt;GroupChat&gt; 更改为List&lt;GroupChat&gt;。另外,尝试使该查询原生

标签: mysql hibernate spring-boot spring-data-jpa jpql


【解决方案1】:

由于这涉及到 JPQL 中的复杂查询,因此最好使用 Native Query。

@Query(value="select g from GroupChat g  
              join g.route r  
              join r.bus b 
              join b.mostRecentStop
              join r.stops s
              join s.children c 
              where r.routeId = :routeId
              and s.stopTime <= mrs.stopTime
              and g.childId = c.childId",
              nativeQuery=true
      )
Set<GroupChat> getAllGroupChatsOnRouteForPreviousStops(@Param("routeId") short routeId);

【讨论】:

  • 设法通过使用本机查询删除连接并解决问题!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
  • 2014-08-03
  • 2017-12-12
  • 1970-01-01
相关资源
最近更新 更多