我有这样的JPA存储库和JPQL查询:
@Query("SELECT c from Campaign c" +
" left join fetch c.postsList p on p.status = :postStatus" +
" left join fetch p.platform" +
" left join fetch c.campaignStatistics stat on stat.updateDate = :updateDate" +
" where c.id =:id")
Campaign findCampaignWithPosts(
@Param("id") Long id,
@Param("postStatus") PostStatus postStatus,
@Param("updateDate") LocalDate updateDate);但这不管用。我得到:
org.hibernate.hql.internal.ast.QuerySyntaxException: with-clause not allowed on fetched associations; use filters我研究了有关JPA2.1规范的信息,这就是我发现的:
连接使用的联接条件来自映射的联接列。这意味着JPQL用户通常不需要知道每个关系是如何连接的。在某些情况下,在联接条件中附加附加条件是可取的,通常是在外部联接的情况下。这可以通过ON子句来完成。ON子句是在JPA2.1指定中定义的,一些JPA提供程序可能支持该子句。EclipseLink : Hibernate : TopLink -支持ON子句。
应该注意的是,这种类型的查询根本帮不了我,因为在这个查询中,有时我会得到null,其中子句在联接表之后使用。
@Query("SELECT c from Campaign c" +
" left join fetch c.postsList p" +
" left join fetch p.platform" +
" left join fetch c.campaignStatistics stat" +
" where c.id =:id" +
" and p.status = :postStatus" +
" and stat.updateDate = :updateDate")在这种情况下该怎么办?除了如何使用本机查询之外,是否没有其他解决方案?但是,几乎所有JPQL查询的意义都消失了。我使用hibernate版本5.2.12
发布于 2017-12-26 15:40:50
当您添加和p.status = :postStatus时,您是对的,它过滤掉了不存在join右侧的结果(即当活动没有帖子时)。
对我起作用的是添加一个OR子句,以接受连接的右侧为NULL的情况。
因此,您应该将and p.status = :postStatus替换为and (p IS NULL OR p.status = :postStatus)。
因此,这一请求应该有效:
@Query("SELECT c from Campaign c" +
" left join fetch c.postsList p" +
" left join fetch p.platform" +
" left join fetch c.campaignStatistics stat" +
" where c.id =:id" +
" and (p is NULL OR p.status = :postStatus)" +
" and stat.updateDate = :updateDate")至于您收到的错误消息,我认为您不应该添加ON子句,因为这已经由JPA/Hibernate处理了。
我正在使用Hibernate 5.0.12。
发布于 2021-02-02 09:28:51
没有替代的解决方案,因为当您有这样的谓词时:
and (p is NULL OR p.status = :postStatus)然后出现3起案件:
在状态从3的情况下,你将失去所有行与竞选完全。但是获取状态为1的
因为左联接不会加入空,所以当postList列表不是空时。
发布于 2018-03-06 12:52:35
它是not a good idea在获取别名时使用的条件
尝尝这个
@Query("SELECT c from Campaign c" +
" left join c.postsList p" +
" left join fetch c.postsList " +
" left join fetch p.platform " +
" left join c.campaignStatistics stat" +
" left join fetch c.campaignStatistics " +
" where c.id =:id" +
" and (p is NULL OR p.status = :postStatus)" +
" and stat.updateDate = :updateDate")https://stackoverflow.com/questions/47543667
复制相似问题