Skip to content

Commit

Permalink
Implement FluentQuery for Querydsl and Query by Example.
Browse files Browse the repository at this point in the history
Add support for both QueryByExampleExecutor and QuerydslPredicateExecutor. This is used in SimpleJpaRepository and QuerydslJpaPredicateExecutor, resulting in various test cases proving support by both examples and Querydsl predicates.

NOTE: Class-based DTOs are NOT supported yet.

Closes #2294.

Related: #2327.
  • Loading branch information
gregturn committed Oct 7, 2021
1 parent 8592dec commit 64beaab
Show file tree
Hide file tree
Showing 12 changed files with 875 additions and 28 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
<hibernate>5.5.3.Final</hibernate>
<mysql-connector-java>8.0.23</mysql-connector-java>
<postgresql>42.2.19</postgresql>
<springdata.commons>2.6.0-SNAPSHOT</springdata.commons>
<springdata.commons>2.6.0-2228-SNAPSHOT</springdata.commons>
<vavr>0.10.3</vavr>

<hibernate.groupId>org.hibernate</hibernate.groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,8 +144,8 @@ protected Predicate or(Predicate base, Predicate predicate) {

/**
* Finalizes the given {@link Predicate} and applies the given sort. Delegates to
* {@link #complete(Predicate, Sort, CriteriaQuery, CriteriaBuilder, Root)} and hands it the current {@link CriteriaQuery}
* and {@link CriteriaBuilder}.
* {@link #complete(Predicate, Sort, CriteriaQuery, CriteriaBuilder, Root)} and hands it the current
* {@link CriteriaQuery} and {@link CriteriaBuilder}.
*/
@Override
protected final CriteriaQuery<? extends Object> complete(Predicate predicate, Sort sort) {
Expand Down Expand Up @@ -271,10 +271,12 @@ public Predicate build() {
return getTypedPath(root, part).isNotNull();
case NOT_IN:
// cast required for eclipselink workaround, see DATAJPA-433
return upperIfIgnoreCase(getTypedPath(root, part)).in((Expression<Collection<?>>) provider.next(part, Collection.class).getExpression()).not();
return upperIfIgnoreCase(getTypedPath(root, part))
.in((Expression<Collection<?>>) provider.next(part, Collection.class).getExpression()).not();
case IN:
// cast required for eclipselink workaround, see DATAJPA-433
return upperIfIgnoreCase(getTypedPath(root, part)).in((Expression<Collection<?>>) provider.next(part, Collection.class).getExpression());
return upperIfIgnoreCase(getTypedPath(root, part))
.in((Expression<Collection<?>>) provider.next(part, Collection.class).getExpression());
case STARTING_WITH:
case ENDING_WITH:
case CONTAINING:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* Copyright 2021 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jpa.repository.support;

import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.query.EscapeCharacter;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.lang.Nullable;

/**
* Immutable implementation of {@link FetchableFluentQuery} based on Query by {@link Example}. All methods that return a
* {@link FetchableFluentQuery} will return a new instance, not the original.
*
* @param <S> Domain type
* @param <R> Result type
* @author Greg Turnquist
* @since 2.6
*/
class FetchableFluentQueryByExample<S, R> extends FluentQuerySupport<R> implements FetchableFluentQuery<R> {

private final Example<S> example;
private final Function<Sort, TypedQuery<S>> finder;
private final Function<Example<S>, Long> countOperation;
private final Function<Example<S>, Boolean> existsOperation;
private final EntityManager entityManager;
private final EscapeCharacter escapeCharacter;

public FetchableFluentQueryByExample(Example<S> example, Function<Sort, TypedQuery<S>> finder,
Function<Example<S>, Long> countOperation, Function<Example<S>, Boolean> existsOperation,
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context,
EntityManager entityManager, EscapeCharacter escapeCharacter) {
this(example, (Class<R>) example.getProbeType(), Sort.unsorted(), null, finder, countOperation, existsOperation,
context, entityManager, escapeCharacter);
}

private FetchableFluentQueryByExample(Example<S> example, Class<R> returnType, Sort sort,
@Nullable Collection<String> properties, Function<Sort, TypedQuery<S>> finder,
Function<Example<S>, Long> countOperation, Function<Example<S>, Boolean> existsOperation,
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context,
EntityManager entityManager, EscapeCharacter escapeCharacter) {

super(returnType, sort, properties, context);
this.example = example;
this.finder = finder;
this.countOperation = countOperation;
this.existsOperation = existsOperation;
this.entityManager = entityManager;
this.escapeCharacter = escapeCharacter;
}

@Override
public FetchableFluentQuery<R> sortBy(Sort sort) {

return new FetchableFluentQueryByExample<S, R>(this.example, this.resultType, this.sort.and(sort), this.properties,
this.finder, this.countOperation, this.existsOperation, this.context, this.entityManager, this.escapeCharacter);
}

@Override
public <NR> FetchableFluentQuery<NR> as(Class<NR> resultType) {

if (!resultType.isInterface()) {
throw new UnsupportedOperationException("Class-based DTOs are not yet supported.");
}

return new FetchableFluentQueryByExample<S, NR>(this.example, resultType, this.sort, this.properties, this.finder,
this.countOperation, this.existsOperation, this.context, this.entityManager, this.escapeCharacter);
}

@Override
public FetchableFluentQuery<R> project(Collection<String> properties) {

return new FetchableFluentQueryByExample<>(this.example, this.resultType, this.sort, mergeProperties(properties),
this.finder, this.countOperation, this.existsOperation, this.context, this.entityManager, this.escapeCharacter);
}

@Override
public R oneValue() {

TypedQuery<S> limitedQuery = this.finder.apply(this.sort);
limitedQuery.setMaxResults(2); // Never need more than 2 values

List<R> results = limitedQuery //
.getResultStream() //
.map(getConversionFunction(this.example.getProbeType(), this.resultType)) //
.collect(Collectors.toList());
;

if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1);
}

return results.isEmpty() ? null : results.get(0);
}

@Override
public R firstValue() {

TypedQuery<S> limitedQuery = this.finder.apply(this.sort);
limitedQuery.setMaxResults(1); // Never need more than 1 value

List<R> results = limitedQuery //
.getResultStream() //
.map(getConversionFunction(this.example.getProbeType(), this.resultType)) //
.collect(Collectors.toList());

return results.isEmpty() ? null : results.get(0);
}

@Override
public List<R> all() {
return stream().collect(Collectors.toList());
}

@Override
public Page<R> page(Pageable pageable) {
return pageable.isUnpaged() ? new PageImpl<>(all()) : readPage(pageable);
}

@Override
public Stream<R> stream() {

return this.finder.apply(this.sort) //
.getResultStream() //
.map(getConversionFunction(this.example.getProbeType(), this.resultType));
}

@Override
public long count() {
return this.countOperation.apply(example);
}

@Override
public boolean exists() {
return this.existsOperation.apply(example);
}

private Page<R> readPage(Pageable pageable) {

TypedQuery<S> pagedQuery = this.finder.apply(this.sort);

if (pageable.isPaged()) {
pagedQuery.setFirstResult((int) pageable.getOffset());
pagedQuery.setMaxResults(pageable.getPageSize());
}

List<R> paginatedResults = pagedQuery.getResultStream() //
.map(getConversionFunction(this.example.getProbeType(), this.resultType)) //
.collect(Collectors.toList());

return PageableExecutionUtils.getPage(paginatedResults, pageable, () -> this.countOperation.apply(this.example));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
/*
* Copyright 2021 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.jpa.repository.support;

import java.util.Collection;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mapping.PersistentEntity;
import org.springframework.data.mapping.PersistentProperty;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.lang.Nullable;

import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.JPQLQuery;

/**
* Immutable implementation of {@link FetchableFluentQuery} based on a Querydsl {@link Predicate}. All methods that
* return a {@link FetchableFluentQuery} will return a new instance, not the original.
*
* @param <S> Domain type
* @param <R> Result type
* @author Greg Turnquist
* @since 2.6
*/
class FetchableFluentQueryByPredicate<S, R> extends FluentQuerySupport<R> implements FetchableFluentQuery<R> {

private final Predicate predicate;
private final Function<Sort, JPQLQuery<S>> finder;
private final BiFunction<Sort, Pageable, JPQLQuery<S>> pagedFinder;
private final Function<Predicate, Long> countOperation;
private final Function<Predicate, Boolean> existsOperation;
private final Class<S> entityType;

public FetchableFluentQueryByPredicate(Predicate predicate, Class<R> resultType, Function<Sort, JPQLQuery<S>> finder,
BiFunction<Sort, Pageable, JPQLQuery<S>> pagedFinder, Function<Predicate, Long> countOperation,
Function<Predicate, Boolean> existsOperation, Class<S> entityType,
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context) {
this(predicate, resultType, Sort.unsorted(), null, finder, pagedFinder, countOperation, existsOperation, entityType,
context);
}

private FetchableFluentQueryByPredicate(Predicate predicate, Class<R> resultType, Sort sort,
@Nullable Collection<String> properties, Function<Sort, JPQLQuery<S>> finder,
BiFunction<Sort, Pageable, JPQLQuery<S>> pagedFinder, Function<Predicate, Long> countOperation,
Function<Predicate, Boolean> existsOperation, Class<S> entityType,
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context) {

super(resultType, sort, properties, context);
this.predicate = predicate;
this.finder = finder;
this.pagedFinder = pagedFinder;
this.countOperation = countOperation;
this.existsOperation = existsOperation;
this.entityType = entityType;
}

@Override
public FetchableFluentQuery<R> sortBy(Sort sort) {

return new FetchableFluentQueryByPredicate<>(this.predicate, this.resultType, this.sort.and(sort), this.properties,
this.finder, this.pagedFinder, this.countOperation, this.existsOperation, this.entityType, this.context);
}

@Override
public <NR> FetchableFluentQuery<NR> as(Class<NR> resultType) {

if (!resultType.isInterface()) {
throw new UnsupportedOperationException("Class-based DTOs are not yet supported.");
}

return new FetchableFluentQueryByPredicate<>(this.predicate, resultType, this.sort, this.properties, this.finder,
this.pagedFinder, this.countOperation, this.existsOperation, this.entityType, this.context);
}

@Override
public FetchableFluentQuery<R> project(Collection<String> properties) {

return new FetchableFluentQueryByPredicate<>(this.predicate, this.resultType, this.sort,
mergeProperties(properties), this.finder, this.pagedFinder, this.countOperation, this.existsOperation,
this.entityType, this.context);
}

@Override
public R oneValue() {

List<R> results = this.finder.apply(this.sort) //
.limit(2) // Never need more than 2 values
.stream() //
.map(getConversionFunction(this.entityType, this.resultType)) //
.collect(Collectors.toList());

if (results.size() > 1) {
throw new IncorrectResultSizeDataAccessException(1);
}

return results.isEmpty() ? null : results.get(0);
}

@Override
public R firstValue() {

List<R> results = this.finder.apply(this.sort) //
.limit(1) // Never need more than 1 value
.stream() //
.map(getConversionFunction(this.entityType, this.resultType)) //
.collect(Collectors.toList());

return results.isEmpty() ? null : results.get(0);
}

@Override
public List<R> all() {
return stream().collect(Collectors.toList());
}

@Override
public Page<R> page(Pageable pageable) {
return pageable.isUnpaged() ? new PageImpl<>(all()) : readPage(pageable);
}

@Override
public Stream<R> stream() {

return this.finder.apply(this.sort) //
.stream() //
.map(getConversionFunction(this.entityType, this.resultType));
}

@Override
public long count() {
return this.countOperation.apply(this.predicate);
}

@Override
public boolean exists() {
return this.existsOperation.apply(this.predicate);
}

private Page<R> readPage(Pageable pageable) {

JPQLQuery<S> pagedQuery = this.pagedFinder.apply(this.sort, pageable);

List<R> paginatedResults = pagedQuery.stream() //
.map(getConversionFunction(this.entityType, this.resultType)) //
.collect(Collectors.toList());

return PageableExecutionUtils.getPage(paginatedResults, pageable, () -> this.countOperation.apply(this.predicate));
}
}
Loading

0 comments on commit 64beaab

Please sign in to comment.