Skip to content

Commit 08488e3

Browse files
Prevent unnecessary query when no results are found by the count query
1 parent eae000f commit 08488e3

File tree

3 files changed

+13
-6
lines changed

3 files changed

+13
-6
lines changed

src/main/java/org/springframework/data/jpa/datatables/mapping/DataTablesOutput.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,14 @@ public class DataTablesOutput<T> {
1919
* Total records, before filtering (i.e. the total number of records in the database)
2020
*/
2121
@JsonView(View.class)
22-
private Long recordsTotal;
22+
private Long recordsTotal = 0L;
2323

2424
/**
2525
* Total records, after filtering (i.e. the total number of records after filtering has been
2626
* applied - not just the number of records being returned for this page of data).
2727
*/
2828
@JsonView(View.class)
29-
private Long recordsFiltered;
29+
private Long recordsFiltered = 0L;
3030

3131
/**
3232
* The data to be displayed in the table. This is an array of data source objects, one for each

src/main/java/org/springframework/data/jpa/datatables/qrepository/QDataTablesRepositoryImpl.java

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,11 @@ public DataTablesOutput<T> findAll(DataTablesInput input, Predicate additionalPr
6262
DataTablesOutput<T> output = new DataTablesOutput<T>();
6363
output.setDraw(input.getDraw());
6464
try {
65-
output
66-
.setRecordsTotal(preFilteringPredicate == null ? count() : count(preFilteringPredicate));
65+
long recordsTotal = preFilteringPredicate == null ? count() : count(preFilteringPredicate);
66+
if (recordsTotal == 0) {
67+
return output;
68+
}
69+
output.setRecordsTotal(recordsTotal);
6770

6871
Page<T> data = findAll(new BooleanBuilder().and(getPredicate(this.builder, input))
6972
.and(additionalPredicate).and(preFilteringPredicate).getValue(), getPageable(input));

src/main/java/org/springframework/data/jpa/datatables/repository/DataTablesRepositoryImpl.java

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,12 @@ public DataTablesOutput<T> findAll(DataTablesInput input,
4747
output.setDraw(input.getDraw());
4848

4949
try {
50-
output.setRecordsTotal(
51-
preFilteringSpecification == null ? count() : count(preFilteringSpecification));
50+
long recordsTotal =
51+
preFilteringSpecification == null ? count() : count(preFilteringSpecification);
52+
if (recordsTotal == 0) {
53+
return output;
54+
}
55+
output.setRecordsTotal(recordsTotal);
5256

5357
Page<T> data = findAll(Specifications.where(getSpecification(getDomainClass(), input))
5458
.and(additionalSpecification).and(preFilteringSpecification), getPageable(input));

0 commit comments

Comments
 (0)