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



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

现在,我想使用自定义查询,在其中联接多个实体,并在这些实体上定义一些 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 子句及其限制之上。

您可以使用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")

另外,看看弗拉德·米哈尔恰的这个答案:

FetchMode 在 Spring Data JPA 中是如何工作的

最新更新