Skip to content

Commit 752544a

Browse files
christophstroblmp911de
authored andcommitted
DATAMONGO-2149 - Fix $slice in fields projection when pointing to array of DBRefs.
We now no longer try to convert the actual slice parameters into a DBRef. Original pull request: #623.
1 parent 1e4cc2e commit 752544a

File tree

4 files changed

+105
-1
lines changed

4 files changed

+105
-1
lines changed

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java

+13-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import java.util.ArrayList;
1919
import java.util.Arrays;
2020
import java.util.Collections;
21+
import java.util.HashSet;
2122
import java.util.Iterator;
2223
import java.util.List;
2324
import java.util.Map.Entry;
@@ -284,7 +285,7 @@ protected Document getMappedKeyword(Keyword keyword, @Nullable MongoPersistentEn
284285
*/
285286
protected Document getMappedKeyword(Field property, Keyword keyword) {
286287

287-
boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists();
288+
boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists() && keyword.mayHoldDbRef();
288289
Object value = keyword.getValue();
289290

290291
Object convertedValue = needsAssociationConversion ? convertAssociation(value, property)
@@ -603,10 +604,12 @@ protected boolean isKeyword(String candidate) {
603604
static class Keyword {
604605

605606
private static final String N_OR_PATTERN = "\\$.*or";
607+
private static final Set<String> NON_DBREF_CONVERTING_KEYWORDS = new HashSet<>(Arrays.asList("$", "$size", "$slice", "$gt", "$lt"));
606608

607609
private final String key;
608610
private final Object value;
609611

612+
610613
public Keyword(Bson source, String key) {
611614
this.key = key;
612615
this.value = BsonUtils.get(source, key);
@@ -666,6 +669,15 @@ public String getKey() {
666669
public <T> T getValue() {
667670
return (T) value;
668671
}
672+
673+
/**
674+
*
675+
* @return {@literal true} if key may hold a DbRef.
676+
* @since 2.0.13
677+
*/
678+
public boolean mayHoldDbRef() {
679+
return !NON_DBREF_CONVERTING_KEYWORDS.contains(key);
680+
}
669681
}
670682

671683
/**

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java

+71
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,16 @@
2727
import java.util.HashSet;
2828
import java.util.List;
2929
import java.util.Optional;
30+
import java.util.Set;
3031
import java.util.UUID;
3132
import java.util.regex.Pattern;
3233
import java.util.stream.Collectors;
34+
import java.util.stream.IntStream;
3335
import java.util.stream.Stream;
3436

3537
import org.hamcrest.Matchers;
3638
import org.junit.Before;
39+
import org.junit.Ignore;
3740
import org.junit.Rule;
3841
import org.junit.Test;
3942
import org.junit.rules.ExpectedException;
@@ -60,6 +63,7 @@
6063
import org.springframework.data.mongodb.core.MongoOperations;
6164
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
6265
import org.springframework.data.mongodb.core.query.BasicQuery;
66+
import org.springframework.data.mongodb.core.query.Query;
6367
import org.springframework.data.mongodb.repository.Person.Sex;
6468
import org.springframework.data.mongodb.repository.SampleEvaluationContextExtension.SampleSecurityContextHolder;
6569
import org.springframework.data.querydsl.QSort;
@@ -1220,4 +1224,71 @@ public void findByRegexWithPatternAndOptions() {
12201224
assertThat(repository.findByFirstnameRegex(Pattern.compile(fn))).hasSize(0);
12211225
assertThat(repository.findByFirstnameRegex(Pattern.compile(fn, Pattern.CASE_INSENSITIVE))).hasSize(1);
12221226
}
1227+
1228+
@Test // DATAMONGO-2149
1229+
public void annotatedQueryShouldAllowSliceInFieldsProjectionWithDbRef() {
1230+
1231+
operations.remove(new Query(), User.class);
1232+
1233+
List<User> users = IntStream.range(0, 10).mapToObj(it -> {
1234+
1235+
User user = new User();
1236+
user.id = "id" + it;
1237+
user.username = "user" + it;
1238+
1239+
return user;
1240+
}).collect(Collectors.toList());
1241+
1242+
users.forEach(operations::save);
1243+
1244+
alicia.fans = new ArrayList<>(users);
1245+
operations.save(alicia);
1246+
1247+
Person target = repository.findWithSliceInProjection(alicia.getId(), 0, 5);
1248+
assertThat(target.getFans().size()).isEqualTo(5);
1249+
}
1250+
1251+
@Test // DATAMONGO-2149
1252+
public void annotatedQueryShouldAllowPositionalParameterInFieldsProjection() {
1253+
1254+
Set<Address> addressList = IntStream.range(0, 10).mapToObj(it -> new Address("street-" + it, "zip", "lnz"))
1255+
.collect(Collectors.toSet());
1256+
1257+
alicia.setShippingAddresses(addressList);
1258+
operations.save(alicia);
1259+
1260+
Person target = repository.findWithArrayPositionInProjection(1);
1261+
1262+
assertThat(target).isNotNull();
1263+
assertThat(target.getShippingAddresses()).hasSize(1);
1264+
}
1265+
1266+
@Test // DATAMONGO-2149
1267+
@Ignore("This one fails due to Json parse exception within MongoDB")
1268+
public void annotatedQueryShouldAllowPositionalParameterInFieldsProjectionWithDbRef() {
1269+
1270+
// the following needs to be added to PersonRepository.
1271+
1272+
// @Query(value = "{ 'fans' : { '$elemMatch' : { '$ref' : 'user' } } }", fields = "{ 'fans.$': ?0 }")
1273+
// Person findWithArrayPositionInProjectionWithDbRef(int position);
1274+
1275+
List<User> userList = IntStream.range(0, 10).mapToObj(it -> {
1276+
1277+
User user = new User();
1278+
user.id = "" + it;
1279+
user.username = "user" + it;
1280+
1281+
return user;
1282+
}).collect(Collectors.toList());
1283+
1284+
userList.forEach(operations::save);
1285+
1286+
alicia.setFans(userList);
1287+
operations.save(alicia);
1288+
1289+
// Person target = repository.findWithArrayPositionInProjectionWithDbRef(1);
1290+
//
1291+
// assertThat(target).isNotNull();
1292+
// assertThat(target.getShippingAddresses()).hasSize(1);
1293+
}
12231294
}

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/PersonRepository.java

+6
Original file line numberDiff line numberDiff line change
@@ -350,4 +350,10 @@ Page<Person> findByCustomQueryLastnameAndAddressStreetInList(String lastname, Li
350350
Iterable<PersonSummary> findClosedProjectionBy();
351351

352352
List<Person> findByFirstnameRegex(Pattern pattern);
353+
354+
@Query(value = "{ 'id' : ?0 }", fields = "{ 'fans': { '$slice': [ ?1, ?2 ] } }")
355+
Person findWithSliceInProjection(String id, int skip, int limit);
356+
357+
@Query(value = "{ 'shippingAddresses' : { '$elemMatch' : { 'city' : { '$eq' : 'lnz' } } } }", fields = "{ 'shippingAddresses.$': ?0 }")
358+
Person findWithArrayPositionInProjection(int position);
353359
}

spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQueryUnitTests.java

+15
Original file line numberDiff line numberDiff line change
@@ -603,6 +603,18 @@ public void spelShouldIgnoreJsonParseErrorsForRegex() {
603603
is(new BasicQuery("{lastname: {$regex: 'Chandler'}}").getQueryObject().toJson()));
604604
}
605605

606+
@Test // DATAMONGO-2149
607+
public void shouldParseFieldsProjectionWithSliceCorrectly() {
608+
609+
StringBasedMongoQuery mongoQuery = createQueryForMethod("findWithSliceInProjection", String.class, int.class,
610+
int.class);
611+
ConvertingParameterAccessor accessor = StubParameterAccessor.getAccessor(converter, "Bruce Banner", 0, 5);
612+
613+
org.springframework.data.mongodb.core.query.Query query = mongoQuery.createQuery(accessor);
614+
615+
assertThat(query.getFieldsObject(), is(equalTo(Document.parse("{ \"fans\" : { \"$slice\" : [0, 5] } }"))));
616+
}
617+
606618
private StringBasedMongoQuery createQueryForMethod(String name, Class<?>... parameters) {
607619

608620
try {
@@ -718,6 +730,9 @@ private interface SampleRepository extends Repository<Person, Long> {
718730

719731
@Query("{ 'lastname' : { '$regex' : ?#{[0].lastname} } }")
720732
Person findByPersonLastnameRegex(Person key);
733+
734+
@Query(value = "{ 'id' : ?0 }", fields = "{ 'fans': { '$slice': [ ?1, ?2 ] } }")
735+
Person findWithSliceInProjection(String id, int skip, int limit);
721736
}
722737

723738
}

0 commit comments

Comments
 (0)