我想将@EntityGraph与@Query一起使用以避免n + 1问题。
我当前的方法用@Query注释,在此查询中,JPA直接引用实体内部的集合,对其进行过滤并作为结果返回:
@Query(value = "SELECT cv "
+ "FROM CheckMatrixEntity cm "
+ "JOIN cm.checks dc "
+ "JOIN dc.checkVersions cv "
+ "where cm.channelId = :channelId and cm.clientId = :clientId and cm.branchId = :branchId "
+ "and cm.docTypeId = :docTypeId "
+ "and dc.parentCheck is null "
+ "and cv.enabled = true "
+ "and cv.startDate = (select max(cv1.startDate) from CheckVersionEntity cv1 where cv.docCheck=cv1.docCheck and cv1.startDate<=:date)")
List<CheckVersionEntity> actualEnabledChecks(@Param("docTypeId") Long docTypeId,
@Param("channelId") Long channelId,
@Param("clientId") Long clientId,
@Param("branchId") Long branchId,
@Param("date") Date date);
添加@EntityGraph时:
@EntityGraph(value = "CheckMatrixEntity.all", type = LOAD)
@NamedEntityGraph(
name = "CheckMatrixEntity.all",
attributeNodes = {
@NamedAttributeNode("checks")
})
public class CheckMatrixEntity implements Serializable {
我得到一个例外:
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=dc,role=ru.vtb.dbo.bc.domain.db.CheckMatrixEntity.checks,tableName=bc_doc_check,tableAlias=checks1_,origin=bc_check_matrix checkmatri0_,columns={checkmatri0_.matrix_id ,className=ru.vtb.dbo.bc.domain.db.DocCheckEntity}}] [SELECT cv FROM ru.vtb.dbo.bc.domain.db.CheckMatrixEntity cm JOIN cm.checks dc JOIN dc.checkVersions cv where cm.channelId = :channelId and cm.clientId = :clientId and cm.branchId = :branchId and cm.docTypeId = :docTypeId and dc.parentCheck is null and cv.enabled = true and cv.startDate = (select max(cv1.startDate) from ru.vtb.dbo.bc.domain.db.CheckVersionEntity cv1 where cv.docCheck=cv1.docCheck and cv1.startDate<=:date)]; nested exception is java.lang.IllegalArgumentException: org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list [FromElement{explicit,not a collection join,fetch join,fetch non-lazy properties,classAlias=dc,role=ru.vtb.dbo.bc.domain.db.CheckMatrixEntity.checks,tableName=bc_doc_check,tableAlias=checks1_,origin=bc_check_matrix checkmatri0_,columns={checkmatri0_.matrix_id ,className=ru.vtb.dbo.bc.domain.db.DocCheckEntity}}] [SELECT cv FROM ru.vtb.dbo.bc.domain.db.CheckMatrixEntity cm JOIN cm.checks dc JOIN dc.checkVersions cv where cm.channelId = :channelId and cm.clientId = :clientId and cm.branchId = :branchId and cm.docTypeId = :docTypeId and dc.parentCheck is null and cv.enabled = true and cv.startDate = (select max(cv1.startDate) from ru.vtb.dbo.bc.domain.db.CheckVersionEntity cv1 where cv.docCheck=cv1.docCheck and cv1.startDate<=:date)]
但是我不使用提取联接。
我可以使用实体图在查询中使用内部集合吗?