DATAJPA-477 - Avoid query creation in PagedExecution if count query returns 0.

We now skip the query creation if we detect that the preceding count query returned 0 or no results. Previously we always created a query in every case even if it was not necessary.

Original pull request: #113.
This commit is contained in:
Thomas Darimont
2014-11-10 14:14:03 +01:00
committed by Oliver Gierke
parent 7210a5c255
commit fb76c9d422
2 changed files with 26 additions and 2 deletions

View File

@@ -175,10 +175,15 @@ public abstract class JpaQueryExecution {
List<Long> totals = projection.getResultList();
Long total = totals.size() == 1 ? totals.get(0) : totals.size();
Query query = repositoryQuery.createQuery(values);
ParameterAccessor accessor = new ParametersParameterAccessor(parameters, values);
Pageable pageable = accessor.getPageable();
if (total.equals(0L)) {
return new PageImpl<Object>(Collections.emptyList(), pageable, total);
}
Query query = repositoryQuery.createQuery(values);
List<Object> content = pageable == null || total > pageable.getOffset() ? query.getResultList() : Collections
.emptyList();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2008-2013 the original author or authors.
* Copyright 2008-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@ package org.springframework.data.jpa.repository.query;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import java.util.Arrays;
@@ -41,6 +42,7 @@ import org.springframework.data.repository.query.Parameters;
* Unit test for {@link JpaQueryExecution}.
*
* @author Oliver Gierke
* @author Thomas Darimont
*/
@RunWith(MockitoJUnitRunner.class)
public class JpaQueryExecutionUnitTests {
@@ -128,6 +130,23 @@ public class JpaQueryExecutionUnitTests {
verify(query, times(0)).getResultList();
}
/**
* @see DATAJPA-477
*/
@Test
public void pagedExecutionShouldNotGenerateUnecessaryQueryIfCountReportedNoResults() throws Exception {
Parameters<?, ?> parameters = new DefaultParameters(getClass().getMethod("sampleMethod", Pageable.class));
when(jpaQuery.createCountQuery(Mockito.any(Object[].class))).thenReturn(countQuery);
when(countQuery.getResultList()).thenReturn(Arrays.asList(0L));
PagedExecution execution = new PagedExecution(parameters);
execution.doExecute(jpaQuery, new Object[] { new PageRequest(0, 10) });
verify(query, times(0)).getResultList();
verify(jpaQuery, times(0)).createQuery((Object[]) any());
}
public static void sampleMethod(Pageable pageable) {
}