Skip to content

DATAMONGO-952 - Derived query should consider @Query(fields=… #188

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 2 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-mongodb-parent</artifactId>
<version>1.6.0.BUILD-SNAPSHOT</version>
<version>1.6.0.DATAMONGO-952-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
4 changes: 2 additions & 2 deletions spring-data-mongodb-cross-store/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.6.0.BUILD-SNAPSHOT</version>
<version>1.6.0.DATAMONGO-952-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down Expand Up @@ -48,7 +48,7 @@
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.6.0.BUILD-SNAPSHOT</version>
<version>1.6.0.DATAMONGO-952-SNAPSHOT</version>
</dependency>

<dependency>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.6.0.BUILD-SNAPSHOT</version>
<version>1.6.0.DATAMONGO-952-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-log4j/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.6.0.BUILD-SNAPSHOT</version>
<version>1.6.0.DATAMONGO-952-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>1.6.0.BUILD-SNAPSHOT</version>
<version>1.6.0.DATAMONGO-952-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
package org.springframework.data.mongodb.repository.query;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
Expand All @@ -37,6 +39,7 @@
import org.springframework.util.Assert;

import com.mongodb.WriteResult;
import com.mongodb.util.JSON;

/**
* Base class for {@link RepositoryQuery} implementations for Mongo.
Expand All @@ -47,6 +50,7 @@
*/
public abstract class AbstractMongoQuery implements RepositoryQuery {

private static final Pattern PLACEHOLDER = Pattern.compile("\\?(\\d+)");
private static final ConversionService CONVERSION_SERVICE = new DefaultConversionService();

private final MongoQueryMethod method;
Expand Down Expand Up @@ -395,4 +399,22 @@ private Object deleteAndConvertResult(Query query, MongoEntityMetadata<?> metada
return writeResult != null ? writeResult.getN() : 0L;
}
}

protected String replacePlaceholders(String input, ConvertingParameterAccessor accessor) {

Matcher matcher = PLACEHOLDER.matcher(input);
String result = input;

while (matcher.find()) {
String group = matcher.group();
int index = Integer.parseInt(matcher.group(1));
result = result.replace(group, getParameterWithIndex(accessor, index));
}

return result;
}

private String getParameterWithIndex(ConvertingParameterAccessor accessor, int index) {
return JSON.serialize(accessor.getBindableValue(index));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.springframework.data.mongodb.repository.query;

import org.bson.BSONObject;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
Expand All @@ -23,6 +24,10 @@
import org.springframework.data.repository.query.QueryMethod;
import org.springframework.data.repository.query.RepositoryQuery;
import org.springframework.data.repository.query.parser.PartTree;
import org.springframework.util.StringUtils;

import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;

/**
* {@link RepositoryQuery} implementation for Mongo.
Expand Down Expand Up @@ -67,7 +72,41 @@ public PartTree getTree() {
protected Query createQuery(ConvertingParameterAccessor accessor) {

MongoQueryCreator creator = new MongoQueryCreator(tree, accessor, context, isGeoNearQuery);
return creator.createQuery();
Query query = creator.createQuery();

if (StringUtils.hasText(this.getQueryMethod().getFieldSpecification())) {
prepareAndAddFieldSpecification(query, accessor);
}

return query;
}

private void prepareAndAddFieldSpecification(Query query, ConvertingParameterAccessor accessor) {

String fieldString = replacePlaceholders(this.getQueryMethod().getFieldSpecification(), accessor);
Object fieldSpec = failsafeParseJson(fieldString);
if (fieldSpec instanceof BSONObject) {
BSONObject bson = (BSONObject) fieldSpec;
for (String key : bson.keySet()) {
if ("1".equals(bson.get(key).toString())) {
query.fields().include(key);
} else {
query.fields().exclude(key);
}
}
} else {
query.fields().include(fieldString);
}
}

private Object failsafeParseJson(String potentialJson) {

try {
return JSON.parse(potentialJson);
} catch (JSONParseException e) {
// just ignore invalid json
}
return potentialJson;
}

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,12 @@
*/
package org.springframework.data.mongodb.repository.query;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Query;

import com.mongodb.util.JSON;

/**
* Query to use a plain JSON String to create the {@link Query} to actually execute.
*
Expand All @@ -35,7 +30,7 @@
public class StringBasedMongoQuery extends AbstractMongoQuery {

private static final String COUND_AND_DELETE = "Manually defined query for %s cannot be both a count and delete query at the same time!";
private static final Pattern PLACEHOLDER = Pattern.compile("\\?(\\d+)");

private static final Logger LOG = LoggerFactory.getLogger(StringBasedMongoQuery.class);

private final String query;
Expand Down Expand Up @@ -119,21 +114,4 @@ protected boolean isDeleteQuery() {
return this.isDeleteQuery;
}

private String replacePlaceholders(String input, ConvertingParameterAccessor accessor) {

Matcher matcher = PLACEHOLDER.matcher(input);
String result = input;

while (matcher.find()) {
String group = matcher.group();
int index = Integer.parseInt(matcher.group(1));
result = result.replace(group, getParameterWithIndex(accessor, index));
}

return result;
}

private String getParameterWithIndex(ConvertingParameterAccessor accessor, int index) {
return JSON.serialize(accessor.getBindableValue(index));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/*
* Copyright 2014 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
*
* http://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.mongodb.repository.query;

import static org.mockito.Mockito.*;

import java.lang.reflect.Method;

import org.hamcrest.core.IsEqual;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Person;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.core.RepositoryMetadata;

import com.mongodb.BasicDBObjectBuilder;

/**
* @author Christoph Strobl
*/
@RunWith(MockitoJUnitRunner.class)
public class PartTreeMongoQueryUnitTests {

private @Mock RepositoryMetadata metadataMock;
private MongoMappingContext mappingContext;
private @Mock MongoOperations mongoOperationsMock;

@SuppressWarnings({ "unchecked", "rawtypes" })
@Before
public void setUp() {

when(metadataMock.getDomainType()).thenReturn((Class) Person.class);
when(metadataMock.getReturnedDomainClass(Matchers.any(Method.class))).thenReturn((Class) Person.class);
mappingContext = new MongoMappingContext();
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mock(MongoDbFactory.class));
MongoConverter converter = new MappingMongoConverter(dbRefResolver, mappingContext);

when(mongoOperationsMock.getConverter()).thenReturn(converter);
}

/**
* @see DATAMOGO-952
*/
@Test
public void nonJsonSingleFieldRestrictionShouldBeConsidered() {

org.springframework.data.mongodb.core.query.Query query = deriveQueryFromMethod("findByLastname",
new Object[] { "foo" });

Assert.assertThat(query.getFieldsObject(), IsEqual.equalTo(new BasicDBObjectBuilder().add("firstname", 1).get()));
}

/**
* @see DATAMOGO-952
*/
@Test
public void singleFieldJsonIncludeRestrictionShouldBeConsidered() {

org.springframework.data.mongodb.core.query.Query query = deriveQueryFromMethod("findByFirstname",
new Object[] { "foo" });

Assert.assertThat(query.getFieldsObject(), IsEqual.equalTo(new BasicDBObjectBuilder().add("firstname", 1).get()));
}

/**
* @see DATAMOGO-952
*/
@Test
public void multiFieldJsonIncludeRestrictionShouldBeConsidered() {

org.springframework.data.mongodb.core.query.Query query = deriveQueryFromMethod("findByFirstnameAndLastname",
new Object[] { "foo", "bar" });

Assert.assertThat(query.getFieldsObject(),
IsEqual.equalTo(new BasicDBObjectBuilder().add("firstname", 1).add("lastname", 1).get()));
}

/**
* @see DATAMOGO-952
*/
@Test
public void multiFieldJsonExcludeRestrictionShouldBeConsidered() {

org.springframework.data.mongodb.core.query.Query query = deriveQueryFromMethod("findPersonByFirstnameAndLastname",
new Object[] { "foo", "bar" });

Assert.assertThat(query.getFieldsObject(),
IsEqual.equalTo(new BasicDBObjectBuilder().add("firstname", 0).add("lastname", 0).get()));
}

private org.springframework.data.mongodb.core.query.Query deriveQueryFromMethod(String method, Object[] args) {

Class<?>[] types = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
types[i] = args[i].getClass();
}

PartTreeMongoQuery partTreeQuery = createQueryForMethod(method, types);

MongoParameterAccessor accessor = new MongoParametersParameterAccessor(partTreeQuery.getQueryMethod(), args);
return partTreeQuery.createQuery(new ConvertingParameterAccessor(mongoOperationsMock.getConverter(), accessor));
}

private PartTreeMongoQuery createQueryForMethod(String methodName, Class<?>... paramTypes) {

try {

Method method = Repo.class.getMethod(methodName, paramTypes);
MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadataMock, mappingContext);

return new PartTreeMongoQuery(queryMethod, mongoOperationsMock);
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e.getMessage(), e);
} catch (SecurityException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}

private interface Repo extends MongoRepository<Person, Long> {

@Query(fields = "firstname")
Person findByLastname(String lastname);

@Query(fields = "{ 'firstname' : 1 }")
Person findByFirstname(String lastname);

@Query(fields = "{ 'firstname' : 1, 'lastname' : 1 }")
Person findByFirstnameAndLastname(String firstname, String lastname);

@Query(fields = "{ 'firstname' : 0, 'lastname' : 0 }")
Person findPersonByFirstnameAndLastname(String firstname, String lastname);

}

}