【问题标题】:Join multiple entities using where clause and get result from that使用 where 子句加入多个实体并从中获取结果
【发布时间】:2018-01-31 17:47:48
【问题描述】:

我已经成功配置和映射了多个实体,并且一切都按预期工作。

现在我想使用一个自定义查询来连接多个实体并在这些实体上定义一些 where 子句。

public interface GiataItemRepository extends JpaRepository<GiataItem, String>{      
    @Query(value="select g from GiataItem g "
            + "join g.service s "
            + "join s.section se "
            + "join se.secPic sp "
            + "where g.giataId = :giataId "
            + "and se.secScope = 'MAINGALLERY' "
            + "and sp.category = 'MAINGALLERY' "
            + "and sp.seqOrder = 0")
    GiataItem findPicture(@Param("giataId") String giataId);
}

SQL 为我的GiataItem 提供了正确的结果。但是对于所有其他映射实体,如servicesection 等,我的 where 子句没有限制。

我正在使用延迟加载,当我使用giataIetem.getService 时它很清楚,JPA 执行了一个新的选择并且我的 where 子句消失了。

那么,我如何才能让所有加入的实体都建立在 where 子句及其限制之上。

【问题讨论】:

    标签: java spring-boot spring-data-jpa jpql


    【解决方案1】:

    您可以使用JOIN FETCH

    @Query(value="SELECT g FROM GiataItem g "
            + "JOIN FETCH g.service as s "
            + "JOIN FETCH s.section as se "
            + "JOIN FETCH se.secPic as sp "
            + "WHERE g.giataId = :giataId "
            + "AND se.secScope = 'MAINGALLERY' "
            + "AND sp.category = 'MAINGALLERY' "
            + "AND sp.seqOrder = 0")
    

    另外,看看 Vlad Mihalcea 的回答:

    How does the FetchMode work in Spring Data JPA

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      • 2010-10-31
      • 2015-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多