Improve count and exists query projections.

We now use COUNT(*) and SELECT 1 for count respective exists queries to enable database optimizers instead of using the key columns.

Closes #1647
This commit is contained in:
Mark Paluch
2023-11-06 10:35:05 +01:00
parent 5312731623
commit 9ffbfb6f99
3 changed files with 8 additions and 23 deletions

View File

@@ -253,18 +253,11 @@ public class R2dbcEntityTemplate implements R2dbcEntityOperations, BeanFactoryAw
Mono<Long> doCount(Query query, Class<?> entityClass, SqlIdentifier tableName) {
RelationalPersistentEntity<?> entity = getRequiredEntity(entityClass);
StatementMapper statementMapper = dataAccessStrategy.getStatementMapper().forType(entityClass);
StatementMapper.SelectSpec selectSpec = statementMapper //
.createSelect(tableName) //
.doWithTable((table, spec) -> {
Expression countExpression = entity.hasIdProperty()
? table.column(entity.getRequiredIdProperty().getColumnName())
: Expressions.just("1");
return spec.withProjection(Functions.count(countExpression));
});
.withProjection(Functions.count(Expressions.just("*")));
Optional<CriteriaDefinition> criteria = query.getCriteria();
if (criteria.isPresent()) {
@@ -290,17 +283,9 @@ public class R2dbcEntityTemplate implements R2dbcEntityOperations, BeanFactoryAw
Mono<Boolean> doExists(Query query, Class<?> entityClass, SqlIdentifier tableName) {
RelationalPersistentEntity<?> entity = getRequiredEntity(entityClass);
StatementMapper statementMapper = dataAccessStrategy.getStatementMapper().forType(entityClass);
StatementMapper.SelectSpec selectSpec = statementMapper.createSelect(tableName).limit(1);
if (entity.hasIdProperty()) {
selectSpec = selectSpec //
.withProjection(entity.getRequiredIdProperty().getColumnName());
} else {
selectSpec = selectSpec.withProjection(Expressions.just("1"));
}
StatementMapper.SelectSpec selectSpec = statementMapper.createSelect(tableName).limit(1)
.withProjection(Expressions.just("1"));
Optional<CriteriaDefinition> criteria = query.getCriteria();
if (criteria.isPresent()) {