使用 where 子句加入多个实体并从中获取结果

Join multiple entities using where clause and get result from that

我已成功配置和映射多个实体,一切都按预期进行。

现在我想使用自定义查询,在其中加入多个实体并在这些实体上定义一些 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 提供了正确的结果。但是我的 where 子句对所有其他映射实体(如 servicesection 等)没有限制。

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

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

您可以使用 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 的回答: