ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-10 19:00:04  阅读:252  来源: 互联网

标签:join jpa hibernate jpql java


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有