spring-hibernate-query-utils
spring-hibernate-query-utils copied to clipboard
Issue with wrong eager fetch reported
I have following Repository:
public interface ObjectRepository extends JpaRepository<ObjectEntity, Long>,
JpaSpecificationExecutor<ObjectEntity> {
@Query("select distinct so from ObjectEntity so join fetch so.objectAssignmentCounts where so.customerId= :customerId and so.id IN (:ids)")
List<ObjectEntity> getObjectsById(@Param("customerId") Long customerId, @Param("ids") List<Long> ids, Sort sort);
}
In my test code I call my API several times which will call the ObjectRepository.getObjectsById with different paramerts and sorting.
I see that sometimes the testcase fails if running multiple tests in sequence. It seems that the proxy method for the getObjectById is then the same but only the sorting is different. Eg.: proxyMethodName= com.sun.proxy.$Proxy195getObjectsById
initial query: select distinct ... order by obje0_.created_at asc new query: select distinct ... order by obje0_.name asc
This is then causing to increment the select queries count and report an error:
com/yannbriancon/interceptor/HibernateQueryInterceptor.java:212
selectQueriesInfoPerProxyMethod.put(proxyMethodName, selectQueriesInfo.incrementSelectQueriesCount());
2021-05-12 21:28:11.635 ERROR 4168c0df-cbe7-47d7-aa89-18ec834b214f GlobalExceptionHandler:332 - N+1 queries detected with eager fetching on the entity com.test.jpa.model.ObjectEntity
at com.test.service.QueryService.getObjects(QueryService.java:148)
Hint: Missing Lazy fetching configuration on a field of type com.test.jpa.model.ObjectEntity of one of the entities fetched in the query
I can't reproduce it if I debug a single test or try to stop the debugger on this testcase.
I need to set a breakpoint on com/yannbriancon/interceptor/HibernateQueryInterceptor.java:212
while running tests in sequence.
I think it's a mix of a threading/testcase-seperation issue together with the sorting of spring data so that same proxy method is used.
I was able now to reproduce the issue on a single test case. SpringBoot tests are using on my side by default 10 different http-nio-exec threads. After 10 request the existing exec threads are reused with existing SelectQueriesInfos. When now the same query is called on this thread with a different sorting then previously on an older api request then the N+1 query exception is thrown wrongly.