编程语言
首页 > 编程语言> > java-JPQL查询-休眠:获取的关联不允许使用子句

java-JPQL查询-休眠:获取的关联不允许使用子句

作者:互联网

我有这样的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

我去研究了有关JPA 2.1规范的信息,这就是我发现的:

The join condition used for a join comes from the mapping’s join
columns. This means that the JPQL user is normally free from having to
know how every relationship is joined. In some cases it is desirable
to append additional conditions to the join condition, normally in the
case of outer joins. This can be done through the ON clause. The ON
clause is defined in the JPA 2.1 specifiation, and may be supported by
some JPA providers.
EclipseLink : Hibernate : TopLink – support the ON clause.

应当指出,这种查询根本没有帮助我,因为在此查询中有时我会得到null,在联接表之后使用where子句.

   @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查询的含义都丢失了.
我使用休眠版本5.2.12

解决方法:

没错,当添加和p.status =:postStatus时,它会过滤掉不存在联接右侧的结果(即当Campaign没有帖子时).

对我有用的是添加一个OR子句以接受联接右侧为NULL的情况.

因此,您应该使用和替换p.status =:postStatus和(p IS NULL或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.

标签:join,jpa,hibernate,jpql,java
来源: https://codeday.me/bug/20191110/2014644.html