Skip to content

Translate projected properties of the fluent query API into a fetchgraph. #2345

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.6.0-SNAPSHOT</version>
<version>2.6.0-2329-consider-property-paths-SNAPSHOT</version>

<name>Spring Data JPA</name>
<description>Spring Data module for JPA repositories.</description>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* 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.Set;

import javax.persistence.EntityGraph;
import javax.persistence.EntityManager;
import javax.persistence.Subgraph;

import org.springframework.data.mapping.PropertyPath;

/**
* Factory class to create an {@link EntityGraph} from a collection of property paths.
*
* @author Jens Schauder
* @since 2.6
*/
abstract class EntityGraphFactory {

public static final String HINT = "javax.persistence.fetchgraph";

/**
* Create an {@link EntityGraph} from a collection of properties.
*
* @param domainType
* @param properties
*/
public static <T> EntityGraph<T> create(EntityManager entityManager, Class<T> domainType, Set<String> properties) {

EntityGraph<T> entityGraph = entityManager.createEntityGraph(domainType);

for (String property : properties) {

Subgraph<Object> current = null;

for (PropertyPath path : PropertyPath.from(property, domainType)) {

if (path.hasNext()) {
current = current == null ? entityGraph.addSubgraph(path.getSegment())
: current.addSubgraph(path.getSegment());
continue;
}

if (current == null) {
entityGraph.addAttributeNodes(path.getSegment());
} else {
current.addAttributeNodes(path.getSegment());

}
}
}

return entityGraph;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Stream;
Expand All @@ -31,12 +32,8 @@
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;
import org.springframework.util.Assert;

/**
Expand All @@ -47,9 +44,10 @@
* @param <R> Result type
* @author Greg Turnquist
* @author Mark Paluch
* @author Jens Schauder
* @since 2.6
*/
class FetchableFluentQueryByExample<S, R> extends FluentQuerySupport<R> implements FetchableFluentQuery<R> {
class FetchableFluentQueryByExample<S, R> extends FluentQuerySupport<S, R> implements FetchableFluentQuery<R> {

private final Example<S> example;
private final Function<Sort, TypedQuery<S>> finder;
Expand All @@ -60,19 +58,17 @@ class FetchableFluentQueryByExample<S, R> extends FluentQuerySupport<R> implemen

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);
this(example, example.getProbeType(), (Class<R>) example.getProbeType(), Sort.unsorted(), Collections.emptySet(),
finder, countOperation, existsOperation, 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,
private FetchableFluentQueryByExample(Example<S> example, Class<S> entityType, Class<R> returnType, Sort sort,
Collection<String> properties, Function<Sort, TypedQuery<S>> finder, Function<Example<S>, Long> countOperation,
Function<Example<S>, Boolean> existsOperation,
EntityManager entityManager, EscapeCharacter escapeCharacter) {

super(returnType, sort, properties, context);
super(returnType, sort, properties, entityType);
this.example = example;
this.finder = finder;
this.countOperation = countOperation;
Expand All @@ -81,7 +77,7 @@ private FetchableFluentQueryByExample(Example<S> example, Class<R> returnType, S
this.escapeCharacter = escapeCharacter;
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#sortBy(org.springframework.data.domain.Sort)
*/
Expand All @@ -90,11 +86,11 @@ public FetchableFluentQuery<R> sortBy(Sort sort) {

Assert.notNull(sort, "Sort must not be null!");

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

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#as(java.lang.Class)
*/
Expand All @@ -106,29 +102,29 @@ public <NR> FetchableFluentQuery<NR> as(Class<NR> resultType) {
throw new UnsupportedOperationException("Class-based DTOs are not yet supported.");
}

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

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#project(java.util.Collection)
*/
@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);
return new FetchableFluentQueryByExample<>(example, entityType, resultType, sort, mergeProperties(properties),
finder, countOperation, existsOperation, entityManager, escapeCharacter);
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#oneValue()
*/
@Override
public R oneValue() {

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

List<S> results = limitedQuery.getResultList();
Expand All @@ -140,34 +136,34 @@ public R oneValue() {
return results.isEmpty() ? null : getConversionFunction().apply(results.get(0));
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#firstValue()
*/
@Override
public R firstValue() {

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

List<S> results = limitedQuery.getResultList();

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

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#all()
*/
@Override
public List<R> all() {

List<S> resultList = this.finder.apply(this.sort).getResultList();
List<S> resultList = createSortedAndProjectedQuery().getResultList();

return convert(resultList);
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#page(org.springframework.data.domain.Pageable)
*/
Expand All @@ -176,39 +172,39 @@ public Page<R> page(Pageable pageable) {
return pageable.isUnpaged() ? new PageImpl<>(all()) : readPage(pageable);
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#stream()
*/
@Override
public Stream<R> stream() {

return this.finder.apply(this.sort) //
return createSortedAndProjectedQuery() //
.getResultStream() //
.map(getConversionFunction());
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#count()
*/
@Override
public long count() {
return this.countOperation.apply(example);
return countOperation.apply(example);
}

/*
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery#exists()
*/
@Override
public boolean exists() {
return this.existsOperation.apply(example);
return existsOperation.apply(example);
}

private Page<R> readPage(Pageable pageable) {

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

if (pageable.isPaged()) {
pagedQuery.setFirstResult((int) pageable.getOffset());
Expand All @@ -217,7 +213,18 @@ private Page<R> readPage(Pageable pageable) {

List<R> paginatedResults = convert(pagedQuery.getResultList());

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

private TypedQuery<S> createSortedAndProjectedQuery() {

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

if (!properties.isEmpty()) {
query.setHint(EntityGraphFactory.HINT, EntityGraphFactory.create(entityManager, entityType, properties));
}

return query;
}

private List<R> convert(List<S> resultList) {
Expand All @@ -232,7 +239,7 @@ private List<R> convert(List<S> resultList) {
}

private Function<Object, R> getConversionFunction() {
return getConversionFunction(this.example.getProbeType(), this.resultType);
return getConversionFunction(example.getProbeType(), resultType);
}

}
Loading