Skip to content

Commit f4cc010

Browse files
committed
Implement FluentQuery for Querydsl and Query by Example.
Add support for both QueryByExampleExecutor and QuerydslPredicateExecutor. This manifests in SimpleJpaRepository and QuerydslJpaPredicateExecutor, resulting in various test cases proving support by both examples and Querydsl predicates. Closes #2294.
1 parent 8592dec commit f4cc010

13 files changed

+930
-29
lines changed

pom.xml

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
<hibernate>5.5.3.Final</hibernate>
2626
<mysql-connector-java>8.0.23</mysql-connector-java>
2727
<postgresql>42.2.19</postgresql>
28-
<springdata.commons>2.6.0-SNAPSHOT</springdata.commons>
28+
<springdata.commons>2.6.0-2228-SNAPSHOT</springdata.commons>
2929
<vavr>0.10.3</vavr>
3030

3131
<hibernate.groupId>org.hibernate</hibernate.groupId>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package org.springframework.data.jpa.repository.query;
2+
3+
import org.springframework.core.convert.converter.Converter;
4+
import org.springframework.data.mapping.PersistentEntity;
5+
import org.springframework.data.mapping.PersistentProperty;
6+
import org.springframework.data.mapping.PersistentPropertyAccessor;
7+
import org.springframework.data.mapping.PreferredConstructor;
8+
import org.springframework.data.mapping.PreferredConstructor.Parameter;
9+
import org.springframework.data.mapping.SimplePropertyHandler;
10+
import org.springframework.data.mapping.context.MappingContext;
11+
import org.springframework.data.mapping.model.EntityInstantiator;
12+
import org.springframework.data.mapping.model.EntityInstantiators;
13+
import org.springframework.data.mapping.model.ParameterValueProvider;
14+
import org.springframework.util.Assert;
15+
16+
public class DtoInstantiatingConverter implements Converter<Object, Object> {
17+
18+
private final Class<?> targetType;
19+
private final MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context;
20+
private final EntityInstantiator instantiator;
21+
22+
public DtoInstantiatingConverter(Class<?> dtoType,
23+
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context,
24+
EntityInstantiators entityInstantiators) {
25+
26+
Assert.notNull(dtoType, "DTO type must not be null!");
27+
Assert.notNull(context, "MappingContext must not be null!");
28+
Assert.notNull(entityInstantiators, "EntityInstantiators must not be null!");
29+
30+
this.targetType = dtoType;
31+
this.context = context;
32+
System.out.println(this.context.getManagedTypes());
33+
PersistentEntity<?, ? extends PersistentProperty<?>> requiredPersistentEntity = context
34+
.getRequiredPersistentEntity(dtoType);
35+
this.instantiator = entityInstantiators.getInstantiatorFor(requiredPersistentEntity);
36+
}
37+
38+
@Override
39+
@SuppressWarnings({ "rawtypes", "unchecked" })
40+
public Object convert(Object source) {
41+
42+
if (targetType.isInterface()) {
43+
return source;
44+
}
45+
46+
PersistentEntity<?, ?> sourceEntity = context.getRequiredPersistentEntity(source.getClass());
47+
PersistentPropertyAccessor<?> sourceAccessor = sourceEntity.getPropertyAccessor(source);
48+
PersistentEntity<?, ?> targetEntity = context.getRequiredPersistentEntity(targetType);
49+
PreferredConstructor<?, ? extends PersistentProperty<?>> constructor = targetEntity.getPersistenceConstructor();
50+
51+
Object dto = instantiator.createInstance(targetEntity, new ParameterValueProvider() {
52+
53+
@Override
54+
public Object getParameterValue(Parameter parameter) {
55+
return sourceAccessor.getProperty(sourceEntity.getPersistentProperty(parameter.getName()));
56+
}
57+
});
58+
59+
PersistentPropertyAccessor<?> dtoAccessor = targetEntity.getPropertyAccessor(dto);
60+
61+
targetEntity.doWithProperties((SimplePropertyHandler) property -> {
62+
63+
if (constructor.isConstructorParameter(property)) {
64+
return;
65+
}
66+
67+
dtoAccessor.setProperty(property,
68+
sourceAccessor.getProperty(sourceEntity.getPersistentProperty(property.getName())));
69+
});
70+
71+
return dto;
72+
}
73+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
/*
2+
* Copyright 2013-2021 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 static org.springframework.data.jpa.repository.query.QueryUtils.*;
19+
20+
import java.util.Collection;
21+
import java.util.List;
22+
import java.util.function.Function;
23+
import java.util.stream.Collectors;
24+
import java.util.stream.Stream;
25+
26+
import javax.persistence.EntityManager;
27+
import javax.persistence.TypedQuery;
28+
import javax.persistence.criteria.CriteriaBuilder;
29+
import javax.persistence.criteria.CriteriaQuery;
30+
import javax.persistence.criteria.Predicate;
31+
import javax.persistence.criteria.Root;
32+
33+
import org.springframework.dao.IncorrectResultSizeDataAccessException;
34+
import org.springframework.data.domain.Example;
35+
import org.springframework.data.domain.Page;
36+
import org.springframework.data.domain.PageImpl;
37+
import org.springframework.data.domain.Pageable;
38+
import org.springframework.data.domain.Sort;
39+
import org.springframework.data.jpa.convert.QueryByExamplePredicateBuilder;
40+
import org.springframework.data.mapping.PersistentEntity;
41+
import org.springframework.data.mapping.PersistentProperty;
42+
import org.springframework.data.mapping.context.MappingContext;
43+
import org.springframework.data.repository.query.FluentQuery.FetchableFluentQuery;
44+
import org.springframework.data.support.PageableExecutionUtils;
45+
import org.springframework.lang.Nullable;
46+
47+
/**
48+
* Immutable implementation of {@link FetchableFluentQuery} based on Query by {@link Example}. All methods that return a
49+
* {@link FetchableFluentQuery} will return a new instance, not the original.
50+
*
51+
* @param <S> Domain type
52+
* @param <R> Result type
53+
* @author Greg Turnquist
54+
* @author Michael J. Simons
55+
* @author Mark Paluch
56+
* @since 2.6
57+
*/
58+
public class FetchableFluentQueryByExample<S, R> extends FluentQuerySupport<R> implements FetchableFluentQuery<R> {
59+
60+
private Example<S> example;
61+
private Function<Sort, TypedQuery<S>> finder;
62+
private Function<Example<S>, Long> countOperation;
63+
private Function<Example<S>, Boolean> existsOperation;
64+
private EntityManager entityManager;
65+
private EscapeCharacter escapeCharacter;
66+
67+
public FetchableFluentQueryByExample(Example<S> example, Function<Sort, TypedQuery<S>> finder,
68+
Function<Example<S>, Long> countOperation, Function<Example<S>, Boolean> existsOperation,
69+
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context,
70+
EntityManager entityManager, EscapeCharacter escapeCharacter) {
71+
this(example, (Class<R>) example.getProbeType(), Sort.unsorted(), null, finder, countOperation, existsOperation,
72+
context, entityManager, escapeCharacter);
73+
}
74+
75+
private FetchableFluentQueryByExample(Example<S> example, Class<R> returnType, Sort sort,
76+
@Nullable Collection<String> properties, Function<Sort, TypedQuery<S>> finder,
77+
Function<Example<S>, Long> countOperation, Function<Example<S>, Boolean> existsOperation,
78+
MappingContext<? extends PersistentEntity<?, ?>, ? extends PersistentProperty<?>> context,
79+
EntityManager entityManager, EscapeCharacter escapeCharacter) {
80+
81+
super(returnType, sort, properties, context);
82+
this.example = example;
83+
this.finder = finder;
84+
this.countOperation = countOperation;
85+
this.existsOperation = existsOperation;
86+
this.entityManager = entityManager;
87+
this.escapeCharacter = escapeCharacter;
88+
}
89+
90+
@Override
91+
public FetchableFluentQuery<R> sortBy(Sort sort) {
92+
93+
return new FetchableFluentQueryByExample<S, R>(this.example, this.resultType, this.sort.and(sort), this.properties,
94+
this.finder, this.countOperation, this.existsOperation, this.context, this.entityManager, this.escapeCharacter);
95+
}
96+
97+
@Override
98+
public <NR> FetchableFluentQuery<NR> as(Class<NR> resultType) {
99+
100+
return new FetchableFluentQueryByExample<S, NR>(this.example, resultType, this.sort, this.properties, this.finder,
101+
this.countOperation, this.existsOperation, this.context, this.entityManager, this.escapeCharacter);
102+
}
103+
104+
@Override
105+
public FetchableFluentQuery<R> project(Collection<String> properties) {
106+
107+
return new FetchableFluentQueryByExample<>(this.example, this.resultType, this.sort, mergeProperties(properties),
108+
this.finder, this.countOperation, this.existsOperation, this.context, this.entityManager, this.escapeCharacter);
109+
}
110+
111+
@Override
112+
public R oneValue() {
113+
114+
List<R> all = all();
115+
116+
if (all.size() > 1) {
117+
throw new IncorrectResultSizeDataAccessException(1);
118+
}
119+
120+
return all.isEmpty() ? null : all.get(0);
121+
}
122+
123+
@Override
124+
public R firstValue() {
125+
126+
List<R> all = all();
127+
return all.isEmpty() ? null : all.get(0);
128+
}
129+
130+
@Override
131+
public List<R> all() {
132+
return stream().collect(Collectors.toList());
133+
}
134+
135+
@Override
136+
public Page<R> page(Pageable pageable) {
137+
return pageable.isUnpaged() ? new PageImpl<>(all()) : readPage(pageable);
138+
}
139+
140+
@Override
141+
public Stream<R> stream() {
142+
143+
if (this.resultType != this.example.getProbeType()) {
144+
System.out.println("You have a projection!");
145+
}
146+
147+
return this.finder.apply(this.sort) //
148+
.getResultStream() //
149+
.map(getConversionFunction(this.example.getProbeType(), this.resultType));
150+
}
151+
152+
@Override
153+
public long count() {
154+
return this.countOperation.apply(example);
155+
}
156+
157+
@Override
158+
public boolean exists() {
159+
return this.existsOperation.apply(example);
160+
}
161+
162+
private Page<R> readPage(Pageable pageable) {
163+
164+
TypedQuery<S> pagedQuery = this.finder.apply(this.sort);
165+
166+
if (pageable.isPaged()) {
167+
pagedQuery.setFirstResult((int) pageable.getOffset());
168+
pagedQuery.setMaxResults(pageable.getPageSize());
169+
}
170+
171+
List<R> paginatedResults = pagedQuery.getResultStream() //
172+
.map(getConversionFunction(this.example.getProbeType(), this.resultType)) //
173+
.collect(Collectors.toList());
174+
175+
return PageableExecutionUtils.getPage(paginatedResults, pageable, () -> this.countOperation.apply(this.example));
176+
}
177+
178+
/**
179+
* Draft version of a projection-based query using class-based DTOs.
180+
*
181+
* @param sort
182+
* @param queryType
183+
* @param example
184+
* @return
185+
*/
186+
private TypedQuery<R> createProjectionQueryByExample(Sort sort, Class<R> queryType, Example<S> example) {
187+
188+
CriteriaBuilder builder = this.entityManager.getCriteriaBuilder();
189+
CriteriaQuery<R> query = builder.createQuery(queryType);
190+
191+
Root<R> root = query.from(queryType);
192+
query.select(root);
193+
194+
Predicate predicate = QueryByExamplePredicateBuilder.getPredicate(
195+
builder.createQuery(example.getProbeType()).from(example.getProbeType()), builder, example, escapeCharacter);
196+
197+
if (predicate != null) {
198+
query.where(predicate);
199+
}
200+
201+
if (sort.isSorted()) {
202+
query.orderBy(toOrders(sort, root, builder));
203+
}
204+
205+
return this.entityManager.createQuery(query);
206+
}
207+
208+
}

0 commit comments

Comments
 (0)