Skip to content

Commit 1b5dabb

Browse files
mp911deschauder
authored andcommitted
Support for Keyset scrolling.
Closes #2878 Original pull request #2885 See spring-projects/spring-data-commons#2151
1 parent e300bd8 commit 1b5dabb

30 files changed

+1311
-337
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.jpa.repository.query;
17+
18+
import java.util.List;
19+
20+
/**
21+
* Utility methods to obtain sublists.
22+
*
23+
* @author Mark Paluch
24+
*/
25+
class CollectionUtils {
26+
27+
/**
28+
* Return the first {@code count} items from the list.
29+
*
30+
* @param count the number of first elements to be included in the returned list.
31+
* @param list must not be {@literal null}
32+
* @return the returned sublist if the {@code list} is greater {@code count}.
33+
* @param <T>
34+
*/
35+
public static <T> List<T> getFirst(int count, List<T> list) {
36+
37+
if (count > 0 && list.size() > count) {
38+
return list.subList(0, count);
39+
}
40+
41+
return list;
42+
}
43+
44+
/**
45+
* Return the last {@code count} items from the list.
46+
*
47+
* @param count the number of last elements to be included in the returned list.
48+
* @param list must not be {@literal null}
49+
* @return the returned sublist if the {@code list} is greater {@code count}.
50+
* @param <T>
51+
*/
52+
public static <T> List<T> getLast(int count, List<T> list) {
53+
54+
if (count > 0 && list.size() > count) {
55+
return list.subList(list.size() - (count), list.size());
56+
}
57+
58+
return list;
59+
}
60+
61+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/*
2+
* Copyright 2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.jpa.repository.query;
17+
18+
import jakarta.persistence.criteria.CriteriaBuilder;
19+
import jakarta.persistence.criteria.CriteriaQuery;
20+
import jakarta.persistence.criteria.Predicate;
21+
import jakarta.persistence.criteria.Root;
22+
23+
import java.util.Collection;
24+
import java.util.LinkedHashSet;
25+
import java.util.Set;
26+
27+
import org.springframework.data.domain.KeysetScrollPosition;
28+
import org.springframework.data.domain.Sort;
29+
import org.springframework.data.jpa.repository.support.JpaEntityInformation;
30+
import org.springframework.data.repository.query.ReturnedType;
31+
import org.springframework.data.repository.query.parser.PartTree;
32+
import org.springframework.lang.Nullable;
33+
34+
/**
35+
* Extension to {@link JpaQueryCreator} to create queries considering {@link KeysetScrollPosition keyset scrolling}.
36+
*
37+
* @author Mark Paluch
38+
* @since 3.1
39+
*/
40+
class JpaKeysetScrollQueryCreator extends JpaQueryCreator {
41+
42+
private final JpaEntityInformation<?, ?> entityInformation;
43+
private final KeysetScrollPosition scrollPosition;
44+
45+
public JpaKeysetScrollQueryCreator(PartTree tree, ReturnedType type, CriteriaBuilder builder,
46+
ParameterMetadataProvider provider, JpaEntityInformation<?, ?> entityInformation,
47+
KeysetScrollPosition scrollPosition) {
48+
super(tree, type, builder, provider);
49+
this.entityInformation = entityInformation;
50+
this.scrollPosition = scrollPosition;
51+
}
52+
53+
@Override
54+
protected CriteriaQuery<?> complete(@Nullable Predicate predicate, Sort sort, CriteriaQuery<?> query,
55+
CriteriaBuilder builder, Root<?> root) {
56+
57+
KeysetScrollSpecification<Object> keysetSpec = new KeysetScrollSpecification<>(scrollPosition, sort,
58+
entityInformation);
59+
Predicate keysetPredicate = keysetSpec.createPredicate(root, builder);
60+
61+
CriteriaQuery<?> queryToUse = super.complete(predicate, keysetSpec.sort(), query, builder, root);
62+
63+
if (keysetPredicate != null) {
64+
if (queryToUse.getRestriction() != null) {
65+
return queryToUse.where(builder.and(queryToUse.getRestriction(), keysetPredicate));
66+
}
67+
return queryToUse.where(keysetPredicate);
68+
}
69+
70+
return queryToUse;
71+
}
72+
73+
@Override
74+
Collection<String> getRequiredSelection(Sort sort, ReturnedType returnedType) {
75+
76+
Sort sortToUse = KeysetScrollSpecification.createSort(scrollPosition, sort, entityInformation);
77+
78+
Set<String> selection = new LinkedHashSet<>(returnedType.getInputProperties());
79+
sortToUse.forEach(it -> selection.add(it.getProperty()));
80+
81+
return selection;
82+
}
83+
}

Diff for: spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryCreator.java

+6-2
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,6 @@ public List<ParameterMetadata<?>> getParameterExpressions() {
118118

119119
@Override
120120
protected Predicate create(Part part, Iterator<Object> iterator) {
121-
122121
return toPredicate(part, root);
123122
}
124123

@@ -158,9 +157,10 @@ protected CriteriaQuery<? extends Object> complete(@Nullable Predicate predicate
158157

159158
if (returnedType.needsCustomConstruction()) {
160159

160+
Collection<String> requiredSelection = getRequiredSelection(sort, returnedType);
161161
List<Selection<?>> selections = new ArrayList<>();
162162

163-
for (String property : returnedType.getInputProperties()) {
163+
for (String property : requiredSelection) {
164164

165165
PropertyPath path = PropertyPath.from(property, returnedType.getDomainType());
166166
selections.add(toExpressionRecursively(root, path, true).alias(property));
@@ -195,6 +195,10 @@ protected CriteriaQuery<? extends Object> complete(@Nullable Predicate predicate
195195
return predicate == null ? select : select.where(predicate);
196196
}
197197

198+
Collection<String> getRequiredSelection(Sort sort, ReturnedType returnedType) {
199+
return returnedType.getInputProperties();
200+
}
201+
198202
/**
199203
* Creates a {@link Predicate} from the given {@link Part}.
200204
*

Diff for: spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryExecution.java

+34-5
Original file line numberDiff line numberDiff line change
@@ -15,23 +15,25 @@
1515
*/
1616
package org.springframework.data.jpa.repository.query;
1717

18-
import java.lang.reflect.Method;
19-
import java.util.Collection;
20-
import java.util.List;
21-
import java.util.Optional;
22-
2318
import jakarta.persistence.EntityManager;
2419
import jakarta.persistence.NoResultException;
2520
import jakarta.persistence.Query;
2621
import jakarta.persistence.StoredProcedureQuery;
2722

23+
import java.lang.reflect.Method;
24+
import java.util.Collection;
25+
import java.util.List;
26+
import java.util.Optional;
27+
2828
import org.springframework.core.convert.ConversionService;
2929
import org.springframework.core.convert.support.ConfigurableConversionService;
3030
import org.springframework.core.convert.support.DefaultConversionService;
3131
import org.springframework.dao.InvalidDataAccessApiUsageException;
3232
import org.springframework.data.domain.Pageable;
33+
import org.springframework.data.domain.ScrollPosition;
3334
import org.springframework.data.domain.Slice;
3435
import org.springframework.data.domain.SliceImpl;
36+
import org.springframework.data.domain.Sort;
3537
import org.springframework.data.jpa.provider.PersistenceProvider;
3638
import org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor;
3739
import org.springframework.data.support.PageableExecutionUtils;
@@ -128,6 +130,33 @@ protected Object doExecute(AbstractJpaQuery query, JpaParametersParameterAccesso
128130
}
129131
}
130132

133+
/**
134+
* Executes the query to return a {@link org.springframework.data.domain.Window} of entities.
135+
*
136+
* @author Mark Paluch
137+
* @since 3.1
138+
*/
139+
static class ScrollExecution extends JpaQueryExecution {
140+
141+
private final Sort sort;
142+
private final ScrollDelegate<?> delegate;
143+
144+
ScrollExecution(Sort sort, ScrollDelegate<?> delegate) {
145+
this.sort = sort;
146+
this.delegate = delegate;
147+
}
148+
149+
@Override
150+
@SuppressWarnings("unchecked")
151+
protected Object doExecute(AbstractJpaQuery query, JpaParametersParameterAccessor accessor) {
152+
153+
ScrollPosition scrollPosition = accessor.getScrollPosition();
154+
Query scrollQuery = query.createQuery(accessor);
155+
156+
return delegate.scroll(scrollQuery, sort.and(accessor.getSort()), scrollPosition);
157+
}
158+
}
159+
131160
/**
132161
* Executes the query to return a {@link Slice} of entities.
133162
*

Diff for: spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/JpaQueryFactory.java

+10
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import jakarta.persistence.EntityManager;
1919

2020
import org.springframework.data.jpa.repository.QueryRewriter;
21+
import org.springframework.data.repository.query.QueryCreationException;
2122
import org.springframework.data.repository.query.QueryMethodEvaluationContextProvider;
2223
import org.springframework.data.repository.query.RepositoryQuery;
2324
import org.springframework.expression.spel.standard.SpelExpressionParser;
@@ -49,6 +50,10 @@ AbstractJpaQuery fromMethodWithQueryString(JpaQueryMethod method, EntityManager
4950
@Nullable String countQueryString, QueryRewriter queryRewriter,
5051
QueryMethodEvaluationContextProvider evaluationContextProvider) {
5152

53+
if (method.isScrollQuery()) {
54+
throw QueryCreationException.create(method, "Scroll queries are not supported using String-based queries");
55+
}
56+
5257
return method.isNativeQuery()
5358
? new NativeJpaQuery(method, em, queryString, countQueryString, queryRewriter, evaluationContextProvider,
5459
PARSER)
@@ -64,6 +69,11 @@ AbstractJpaQuery fromMethodWithQueryString(JpaQueryMethod method, EntityManager
6469
* @return
6570
*/
6671
public StoredProcedureJpaQuery fromProcedureAnnotation(JpaQueryMethod method, EntityManager em) {
72+
73+
if (method.isScrollQuery()) {
74+
throw QueryCreationException.create(method, "Scroll queries are not supported using stored procedures");
75+
}
76+
6777
return new StoredProcedureJpaQuery(method, em);
6878
}
6979
}

0 commit comments

Comments
 (0)