Browse Source

refactored the Query/Update "DSL" again

pull/1/head
Thomas Risberg 15 years ago
parent
commit
4f32ee1403
  1. 40
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java
  2. 28
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java
  3. 10
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicQuery.java
  4. 70
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicUpdate.java
  5. 28
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java
  6. 2
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/CriteriaDefinition.java
  7. 10
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/OrCriteria.java
  8. 24
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Query.java
  9. 32
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryDefinition.java
  10. 10
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Update.java
  11. 24
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/UpdateDefinition.java
  12. 12
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryCreator.java
  13. 11
      spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java
  14. 11
      spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateTests.java
  15. 30
      spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryTests.java
  16. 2
      spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/SortTests.java
  17. 17
      spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/UpdateTests.java

40
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java

@ -18,8 +18,8 @@ package org.springframework.data.document.mongodb;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
import org.springframework.data.document.mongodb.query.QueryDefinition; import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.UpdateDefinition; import org.springframework.data.document.mongodb.query.Update;
import com.mongodb.CommandResult; import com.mongodb.CommandResult;
import com.mongodb.DBCollection; import com.mongodb.DBCollection;
@ -212,14 +212,14 @@ public interface MongoOperations {
* {@see MongoConverter}. Unless configured otherwise, an * {@see MongoConverter}. Unless configured otherwise, an
* instance of SimpleMongoConverter will be used. * instance of SimpleMongoConverter will be used.
* *
* The query is specified as a {@link QueryDefinition} which can be created either using the {@link BasicQuery} or the more * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}. * feature rich {@link Query}.
* *
* @param query the query class that specifies the criteria used to find a record and also an optional fields specification * @param query the query class that specifies the criteria used to find a record and also an optional fields specification
* @param targetClass the parameterized type of the returned list. * @param targetClass the parameterized type of the returned list.
* @return the List of converted objects * @return the List of converted objects
*/ */
<T> List<T> find(QueryDefinition query, Class<T> targetClass); <T> List<T> find(Query query, Class<T> targetClass);
/** /**
* Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type. * Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type.
@ -228,7 +228,7 @@ public interface MongoOperations {
* {@see MongoConverter}. Unless configured otherwise, an * {@see MongoConverter}. Unless configured otherwise, an
* instance of SimpleMongoConverter will be used. * instance of SimpleMongoConverter will be used.
* *
* The query is specified as a {@link QueryDefinition} which can be created either using the {@link BasicQuery} or the more * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}. * feature rich {@link Query}.
* *
* @param query the query class that specifies the criteria used to find a record and also an optional fields specification * @param query the query class that specifies the criteria used to find a record and also an optional fields specification
@ -236,7 +236,7 @@ public interface MongoOperations {
* @param reader the MongoReader to convert from DBObject to an object. * @param reader the MongoReader to convert from DBObject to an object.
* @return the List of converted objects * @return the List of converted objects
*/ */
<T> List<T> find(QueryDefinition query, Class<T> targetClass, <T> List<T> find(Query query, Class<T> targetClass,
MongoReader<T> reader); MongoReader<T> reader);
/** /**
@ -246,7 +246,7 @@ public interface MongoOperations {
* {@see MongoConverter}. Unless configured otherwise, an * {@see MongoConverter}. Unless configured otherwise, an
* instance of SimpleMongoConverter will be used. * instance of SimpleMongoConverter will be used.
* *
* The query is specified as a {@link QueryDefinition} which can be created either using the {@link BasicQuery} or the more * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}. * feature rich {@link Query}.
* *
* @param collectionName name of the collection to retrieve the objects from * @param collectionName name of the collection to retrieve the objects from
@ -254,7 +254,7 @@ public interface MongoOperations {
* @param targetClass the parameterized type of the returned list. * @param targetClass the parameterized type of the returned list.
* @return the List of converted objects * @return the List of converted objects
*/ */
<T> List<T> find(String collectionName, QueryDefinition query, <T> List<T> find(String collectionName, Query query,
Class<T> targetClass); Class<T> targetClass);
/** /**
@ -264,7 +264,7 @@ public interface MongoOperations {
* {@see MongoConverter}. Unless configured otherwise, an * {@see MongoConverter}. Unless configured otherwise, an
* instance of SimpleMongoConverter will be used. * instance of SimpleMongoConverter will be used.
* *
* The query is specified as a {@link QueryDefinition} which can be created either using the {@link BasicQuery} or the more * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}. * feature rich {@link Query}.
* *
* @param collectionName name of the collection to retrieve the objects from * @param collectionName name of the collection to retrieve the objects from
@ -273,7 +273,7 @@ public interface MongoOperations {
* @param reader the MongoReader to convert from DBObject to an object. * @param reader the MongoReader to convert from DBObject to an object.
* @return the List of converted objects * @return the List of converted objects
*/ */
<T> List<T> find(String collectionName, QueryDefinition query, <T> List<T> find(String collectionName, Query query,
Class<T> targetClass, MongoReader<T> reader); Class<T> targetClass, MongoReader<T> reader);
@ -284,7 +284,7 @@ public interface MongoOperations {
* {@see MongoConverter}. Unless configured otherwise, an * {@see MongoConverter}. Unless configured otherwise, an
* instance of SimpleMongoConverter will be used. * instance of SimpleMongoConverter will be used.
* *
* The query is specified as a {@link QueryDefinition} which can be created either using the {@link BasicQuery} or the more * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more
* feature rich {@link Query}. * feature rich {@link Query}.
* *
* @param collectionName name of the collection to retrieve the objects from * @param collectionName name of the collection to retrieve the objects from
@ -294,7 +294,7 @@ public interface MongoOperations {
* (apply limits, skips and so on). * (apply limits, skips and so on).
* @return the List of converted objects. * @return the List of converted objects.
*/ */
<T> List<T> find(String collectionName, QueryDefinition query, Class<T> targetClass, CursorPreparer preparer); <T> List<T> find(String collectionName, Query query, Class<T> targetClass, CursorPreparer preparer);
/** /**
* Insert the object into the default collection. * Insert the object into the default collection.
@ -434,7 +434,7 @@ public interface MongoOperations {
* @param updateDoc the update document that contains the updated object or $ operators to manipulate the * @param updateDoc the update document that contains the updated object or $ operators to manipulate the
* existing object. * existing object.
*/ */
WriteResult updateFirst(QueryDefinition query, UpdateDefinition update); WriteResult updateFirst(Query query, Update update);
/** /**
* Updates the first object that is found in the specified collection that matches the query document criteria * Updates the first object that is found in the specified collection that matches the query document criteria
@ -445,8 +445,8 @@ public interface MongoOperations {
* @param updateDoc the update document that contains the updated object or $ operators to manipulate the * @param updateDoc the update document that contains the updated object or $ operators to manipulate the
* existing object. * existing object.
*/ */
WriteResult updateFirst(String collectionName, QueryDefinition query, WriteResult updateFirst(String collectionName, Query query,
UpdateDefinition update); Update update);
/** /**
* Updates all objects that are found in the default collection that matches the query document criteria * Updates all objects that are found in the default collection that matches the query document criteria
@ -456,7 +456,7 @@ public interface MongoOperations {
* @param updateDoc the update document that contains the updated object or $ operators to manipulate the * @param updateDoc the update document that contains the updated object or $ operators to manipulate the
* existing object. * existing object.
*/ */
WriteResult updateMulti(QueryDefinition query, UpdateDefinition update); WriteResult updateMulti(Query query, Update update);
/** /**
* Updates all objects that are found in the specified collection that matches the query document criteria * Updates all objects that are found in the specified collection that matches the query document criteria
@ -467,20 +467,20 @@ public interface MongoOperations {
* @param updateDoc the update document that contains the updated object or $ operators to manipulate the * @param updateDoc the update document that contains the updated object or $ operators to manipulate the
* existing object. * existing object.
*/ */
WriteResult updateMulti(String collectionName, QueryDefinition query, WriteResult updateMulti(String collectionName, Query query,
UpdateDefinition update); Update update);
/** /**
* Remove all documents from the default collection that match the provide query document criteria. * Remove all documents from the default collection that match the provide query document criteria.
* @param queryDoc the query document that specifies the criteria used to remove a record * @param queryDoc the query document that specifies the criteria used to remove a record
*/ */
void remove(QueryDefinition query); void remove(Query query);
/** /**
* Remove all documents from the specified collection that match the provide query document criteria. * Remove all documents from the specified collection that match the provide query document criteria.
* @param collectionName name of the collection where the objects will removed * @param collectionName name of the collection where the objects will removed
* @param queryDoc the query document that specifies the criteria used to remove a record * @param queryDoc the query document that specifies the criteria used to remove a record
*/ */
void remove(String collectionName, QueryDefinition query); void remove(String collectionName, Query query);
} }

28
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java

@ -30,8 +30,8 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.document.mongodb.MongoPropertyDescriptors.MongoPropertyDescriptor; import org.springframework.data.document.mongodb.MongoPropertyDescriptors.MongoPropertyDescriptor;
import org.springframework.data.document.mongodb.query.QueryDefinition; import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.UpdateDefinition; import org.springframework.data.document.mongodb.query.Update;
import org.springframework.jca.cci.core.ConnectionCallback; import org.springframework.jca.cci.core.ConnectionCallback;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -407,17 +407,17 @@ public class MongoTemplate implements InitializingBean, MongoOperations {
} }
// Find methods that take a QueryDefinition to express the query. // Find methods that take a Query to express the query.
public <T> List<T> find(QueryDefinition query, Class<T> targetClass) { public <T> List<T> find(Query query, Class<T> targetClass) {
return find(getDefaultCollectionName(), query, targetClass); // return find(getDefaultCollectionName(), query, targetClass); //
} }
public <T> List<T> find(QueryDefinition query, Class<T> targetClass, MongoReader<T> reader) { public <T> List<T> find(Query query, Class<T> targetClass, MongoReader<T> reader) {
return find(getDefaultCollectionName(), query, targetClass, reader); return find(getDefaultCollectionName(), query, targetClass, reader);
} }
public <T> List<T> find(String collectionName, final QueryDefinition query, Class<T> targetClass) { public <T> List<T> find(String collectionName, final Query query, Class<T> targetClass) {
CursorPreparer cursorPreparer = null; CursorPreparer cursorPreparer = null;
if (query.getSkip() > 0 || query.getLimit() > 0 || query.getSortObject() != null) { if (query.getSkip() > 0 || query.getLimit() > 0 || query.getSortObject() != null) {
cursorPreparer = new CursorPreparer() { cursorPreparer = new CursorPreparer() {
@ -444,11 +444,11 @@ public class MongoTemplate implements InitializingBean, MongoOperations {
return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, cursorPreparer); return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, cursorPreparer);
} }
public <T> List<T> find(String collectionName, QueryDefinition query, Class<T> targetClass, MongoReader<T> reader) { public <T> List<T> find(String collectionName, Query query, Class<T> targetClass, MongoReader<T> reader) {
return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, reader); return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, reader);
} }
public <T> List<T> find(String collectionName, QueryDefinition query, public <T> List<T> find(String collectionName, Query query,
Class<T> targetClass, CursorPreparer preparer) { Class<T> targetClass, CursorPreparer preparer) {
return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, preparer); return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, preparer);
} }
@ -613,14 +613,14 @@ public class MongoTemplate implements InitializingBean, MongoOperations {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.document.mongodb.MongoOperations#updateFirst(com.mongodb.DBObject, com.mongodb.DBObject) * @see org.springframework.data.document.mongodb.MongoOperations#updateFirst(com.mongodb.DBObject, com.mongodb.DBObject)
*/ */
public WriteResult updateFirst(QueryDefinition query, UpdateDefinition update) { public WriteResult updateFirst(Query query, Update update) {
return updateFirst(getRequiredDefaultCollectionName(), query, update); return updateFirst(getRequiredDefaultCollectionName(), query, update);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.document.mongodb.MongoOperations#updateFirst(java.lang.String, com.mongodb.DBObject, com.mongodb.DBObject) * @see org.springframework.data.document.mongodb.MongoOperations#updateFirst(java.lang.String, com.mongodb.DBObject, com.mongodb.DBObject)
*/ */
public WriteResult updateFirst(String collectionName, final QueryDefinition query, final UpdateDefinition update) { public WriteResult updateFirst(String collectionName, final Query query, final Update update) {
return execute(new CollectionCallback<WriteResult>() { return execute(new CollectionCallback<WriteResult>() {
public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException { public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException {
WriteResult wr; WriteResult wr;
@ -639,14 +639,14 @@ public class MongoTemplate implements InitializingBean, MongoOperations {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.document.mongodb.MongoOperations#updateMulti(com.mongodb.DBObject, com.mongodb.DBObject) * @see org.springframework.data.document.mongodb.MongoOperations#updateMulti(com.mongodb.DBObject, com.mongodb.DBObject)
*/ */
public WriteResult updateMulti(QueryDefinition query, UpdateDefinition update) { public WriteResult updateMulti(Query query, Update update) {
return updateMulti(getRequiredDefaultCollectionName(), query, update); return updateMulti(getRequiredDefaultCollectionName(), query, update);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.document.mongodb.MongoOperations#updateMulti(java.lang.String, com.mongodb.DBObject, com.mongodb.DBObject) * @see org.springframework.data.document.mongodb.MongoOperations#updateMulti(java.lang.String, com.mongodb.DBObject, com.mongodb.DBObject)
*/ */
public WriteResult updateMulti(String collectionName, final QueryDefinition query, final UpdateDefinition update) { public WriteResult updateMulti(String collectionName, final Query query, final Update update) {
return execute(new CollectionCallback<WriteResult>() { return execute(new CollectionCallback<WriteResult>() {
public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException { public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException {
WriteResult wr = null; WriteResult wr = null;
@ -665,14 +665,14 @@ public class MongoTemplate implements InitializingBean, MongoOperations {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.document.mongodb.MongoOperations#remove(com.mongodb.DBObject) * @see org.springframework.data.document.mongodb.MongoOperations#remove(com.mongodb.DBObject)
*/ */
public void remove(QueryDefinition query) { public void remove(Query query) {
remove(getRequiredDefaultCollectionName(), query); remove(getRequiredDefaultCollectionName(), query);
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.data.document.mongodb.MongoOperations#remove(java.lang.String, com.mongodb.DBObject) * @see org.springframework.data.document.mongodb.MongoOperations#remove(java.lang.String, com.mongodb.DBObject)
*/ */
public void remove(String collectionName, final QueryDefinition query) { public void remove(String collectionName, final Query query) {
execute(new CollectionCallback<Void>() { execute(new CollectionCallback<Void>() {
public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException { public Void doInCollection(DBCollection collection) throws MongoException, DataAccessException {
WriteResult wr = null; WriteResult wr = null;

10
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicQuery.java

@ -18,7 +18,7 @@ package org.springframework.data.document.mongodb.query;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.util.JSON; import com.mongodb.util.JSON;
public class BasicQuery implements QueryDefinition { public class BasicQuery extends Query {
private DBObject queryObject = null; private DBObject queryObject = null;
@ -50,8 +50,14 @@ public class BasicQuery implements QueryDefinition {
this.fieldsObject = fieldsObject; this.fieldsObject = fieldsObject;
} }
@Override
public Query and(Criteria criteria) {
this.queryObject.putAll(criteria.getCriteriaObject());
return this;
}
public DBObject getQueryObject() { public DBObject getQueryObject() {
return queryObject; return this.queryObject;
} }
public DBObject getFieldsObject() { public DBObject getFieldsObject() {

70
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicUpdate.java

@ -15,10 +15,13 @@
*/ */
package org.springframework.data.document.mongodb.query; package org.springframework.data.document.mongodb.query;
import java.util.Collections;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; import com.mongodb.DBObject;
import com.mongodb.util.JSON; import com.mongodb.util.JSON;
public class BasicUpdate implements UpdateDefinition { public class BasicUpdate extends Update {
private DBObject updateObject = null; private DBObject updateObject = null;
@ -32,6 +35,71 @@ public class BasicUpdate implements UpdateDefinition {
this.updateObject = updateObject; this.updateObject = updateObject;
} }
@Override
public Update set(String key, Object value) {
updateObject.put("$set", Collections.singletonMap(key, value));
return this;
}
@Override
public Update unset(String key) {
updateObject.put("$unset", Collections.singletonMap(key, 1));
return this;
}
@Override
public Update inc(String key, long inc) {
updateObject.put("$inc", Collections.singletonMap(key, inc));
return this;
}
@Override
public Update push(String key, Object value) {
updateObject.put("$push", Collections.singletonMap(key, value));
return this;
}
@Override
public Update pushAll(String key, Object[] values) {
DBObject keyValue = new BasicDBObject();
keyValue.put(key, values);
updateObject.put("$pushAll", keyValue);
return this;
}
@Override
public Update addToSet(String key, Object value) {
updateObject.put("$addToSet", Collections.singletonMap(key, value));
return this;
}
@Override
public Update pop(String key, Position pos) {
updateObject.put("$pop", Collections.singletonMap(key, (pos == Position.FIRST ? -1 : 1)));
return this;
}
@Override
public Update pull(String key, Object value) {
updateObject.put("$pull", Collections.singletonMap(key, value));
return this;
}
@Override
public Update pullAll(String key, Object[] values) {
DBObject keyValue = new BasicDBObject();
keyValue.put(key, values);
updateObject.put("$pullAll", keyValue);
return this;
}
@Override
public Update rename(String oldName, String newName) {
updateObject.put("$rename", Collections.singletonMap(oldName, newName));
return this;
}
@Override
public DBObject getUpdateObject() { public DBObject getUpdateObject() {
return updateObject; return updateObject;
} }

28
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java

@ -26,24 +26,22 @@ import com.mongodb.DBObject;
public class Criteria implements CriteriaDefinition { public class Criteria implements CriteriaDefinition {
private Query qb = null; private String key;
private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>(); private LinkedHashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
private Object isValue = null; private Object isValue = null;
public Criteria(Query qb) { public Criteria(String key) {
super(); this.key = key;
this.qb = qb;
} }
public Criteria and(String key) { public static Criteria where(String key) {
return qb.start(key); return new Criteria(key);
} }
public Criteria is(Object o) { public Criteria is(Object o) {
if (isValue != null) { if (isValue != null) {
throw new InvalidDocumentStoreApiUsageException("Multiple 'is' values declared."); throw new InvalidDocumentStoreApiUsageException("Multiple 'is' values declared.");
@ -121,20 +119,20 @@ public class Criteria implements CriteriaDefinition {
criteria.put("$or", queries); criteria.put("$or", queries);
} }
public Query end() { public String getKey() {
return qb; return this.key;
} }
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.datastore.document.mongodb.query.Criteria#getCriteriaObject(java.lang.String) * @see org.springframework.datastore.document.mongodb.query.Criteria#getCriteriaObject(java.lang.String)
*/ */
public DBObject getCriteriaObject(String key) { public DBObject getCriteriaObject() {
DBObject dbo = new BasicDBObject(); DBObject dbo = new BasicDBObject();
boolean not = false; boolean not = false;
for (String k : criteria.keySet()) { for (String k : this.criteria.keySet()) {
if (not) { if (not) {
DBObject notDbo = new BasicDBObject(); DBObject notDbo = new BasicDBObject();
notDbo.put(k, criteria.get(k)); notDbo.put(k, this.criteria.get(k));
dbo.put("$not", notDbo); dbo.put("$not", notDbo);
not = false; not = false;
} }
@ -143,17 +141,17 @@ public class Criteria implements CriteriaDefinition {
not = true; not = true;
} }
else { else {
dbo.put(k, criteria.get(k)); dbo.put(k, this.criteria.get(k));
} }
} }
} }
DBObject queryCriteria = new BasicDBObject(); DBObject queryCriteria = new BasicDBObject();
if (isValue != null) { if (isValue != null) {
queryCriteria.put(key, isValue); queryCriteria.put(this.key, this.isValue);
queryCriteria.putAll(dbo); queryCriteria.putAll(dbo);
} }
else { else {
queryCriteria.put(key, dbo); queryCriteria.put(this.key, dbo);
} }
return queryCriteria; return queryCriteria;
} }

2
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/CriteriaDefinition.java

@ -19,6 +19,6 @@ import com.mongodb.DBObject;
public interface CriteriaDefinition { public interface CriteriaDefinition {
DBObject getCriteriaObject(String key); DBObject getCriteriaObject();
} }

10
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/OrCriteria.java

@ -22,9 +22,9 @@ import com.mongodb.DBObject;
public class OrCriteria implements CriteriaDefinition { public class OrCriteria implements CriteriaDefinition {
QueryDefinition[] queries = null; Query[] queries = null;
public OrCriteria(QueryDefinition[] queries) { public OrCriteria(Query[] queries) {
super(); super();
this.queries = queries; this.queries = queries;
} }
@ -33,13 +33,13 @@ public class OrCriteria implements CriteriaDefinition {
/* (non-Javadoc) /* (non-Javadoc)
* @see org.springframework.datastore.document.mongodb.query.Criteria#getCriteriaObject(java.lang.String) * @see org.springframework.datastore.document.mongodb.query.Criteria#getCriteriaObject(java.lang.String)
*/ */
public DBObject getCriteriaObject(String key) { public DBObject getCriteriaObject() {
DBObject dbo = new BasicDBObject(); DBObject dbo = new BasicDBObject();
BasicBSONList l = new BasicBSONList(); BasicBSONList l = new BasicBSONList();
for (QueryDefinition q : queries) { for (Query q : queries) {
l.add(q.getQueryObject()); l.add(q.getQueryObject());
} }
dbo.put(key, l); dbo.put("$or", l);
return dbo; return dbo;
} }

24
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Query.java

@ -20,7 +20,7 @@ import java.util.LinkedHashMap;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; import com.mongodb.DBObject;
public class Query implements QueryDefinition { public class Query {
private LinkedHashMap<String, CriteriaDefinition> criteria = new LinkedHashMap<String, CriteriaDefinition>(); private LinkedHashMap<String, CriteriaDefinition> criteria = new LinkedHashMap<String, CriteriaDefinition>();
@ -32,17 +32,19 @@ public class Query implements QueryDefinition {
private int limit; private int limit;
public static Criteria startQueryWithCriteria(String key) { public Query() {
return new Query().start(key);
} }
public Criteria start(String key) { public Query(Criteria criteria) {
Criteria c = new Criteria(this); and(criteria);
this.criteria.put(key, c);
return c;
} }
public Query or(QueryDefinition... queries) { public Query and(Criteria criteria) {
this.criteria.put(criteria.getKey(), criteria);
return this;
}
protected Query or(Query... queries) {
this.criteria.put("$or", new OrCriteria(queries)); this.criteria.put("$or", new OrCriteria(queries));
return this; return this;
} }
@ -75,15 +77,11 @@ public class Query implements QueryDefinition {
return this.sort; return this.sort;
} }
// public QueryDefinition build() {
// return this;
// }
public DBObject getQueryObject() { public DBObject getQueryObject() {
DBObject dbo = new BasicDBObject(); DBObject dbo = new BasicDBObject();
for (String k : criteria.keySet()) { for (String k : criteria.keySet()) {
CriteriaDefinition c = criteria.get(k); CriteriaDefinition c = criteria.get(k);
DBObject cl = c.getCriteriaObject(k); DBObject cl = c.getCriteriaObject();
dbo.putAll(cl); dbo.putAll(cl);
} }
return dbo; return dbo;

32
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryDefinition.java

@ -1,32 +0,0 @@
/*
* Copyright 2010-2011 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.document.mongodb.query;
import com.mongodb.DBObject;
public interface QueryDefinition {
DBObject getQueryObject();
DBObject getFieldsObject();
DBObject getSortObject();
int getSkip();
int getLimit();
}

10
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Update.java

@ -22,7 +22,7 @@ import java.util.LinkedHashMap;
import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObject;
import com.mongodb.DBObject; import com.mongodb.DBObject;
public class Update implements UpdateDefinition { public class Update {
public enum Position { public enum Position {
LAST, FIRST LAST, FIRST
@ -30,10 +30,6 @@ public class Update implements UpdateDefinition {
private HashMap<String, Object> criteria = new LinkedHashMap<String, Object>(); private HashMap<String, Object> criteria = new LinkedHashMap<String, Object>();
public static Update startUpdate() {
return new Update();
}
public Update set(String key, Object value) { public Update set(String key, Object value) {
criteria.put("$set", Collections.singletonMap(key, value)); criteria.put("$set", Collections.singletonMap(key, value));
return this; return this;
@ -88,10 +84,6 @@ public class Update implements UpdateDefinition {
return this; return this;
} }
// public UpdateDefinition build() {
// return this;
// }
public DBObject getUpdateObject() { public DBObject getUpdateObject() {
DBObject dbo = new BasicDBObject(); DBObject dbo = new BasicDBObject();
for (String k : criteria.keySet()) { for (String k : criteria.keySet()) {

24
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/UpdateDefinition.java

@ -1,24 +0,0 @@
/*
* Copyright 2010-2011 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.document.mongodb.query;
import com.mongodb.DBObject;
public interface UpdateDefinition {
DBObject getUpdateObject();
}

12
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryCreator.java

@ -15,7 +15,9 @@
*/ */
package org.springframework.data.document.mongodb.repository; package org.springframework.data.document.mongodb.repository;
import java.util.Arrays; import static org.springframework.data.document.mongodb.query.Criteria.where;
import java.util.Collections;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
@ -75,7 +77,7 @@ class MongoQueryCreator extends AbstractQueryCreator<Query, Criteria> {
protected Criteria create(Part part, BindableParameterIterator iterator) { protected Criteria create(Part part, BindableParameterIterator iterator) {
return from(part.getType(), return from(part.getType(),
new Query().start(part.getProperty().toDotPath()), iterator); where(part.getProperty().toDotPath()), iterator);
} }
@ -92,7 +94,7 @@ class MongoQueryCreator extends AbstractQueryCreator<Query, Criteria> {
protected Criteria and(Part part, Criteria base, protected Criteria and(Part part, Criteria base,
BindableParameterIterator iterator) { BindableParameterIterator iterator) {
return from(part.getType(), base.and(part.getProperty().toDotPath()), return from(part.getType(), where(part.getProperty().toDotPath()),
iterator); iterator);
} }
@ -107,7 +109,7 @@ class MongoQueryCreator extends AbstractQueryCreator<Query, Criteria> {
@Override @Override
protected Criteria or(Criteria base, Criteria criteria) { protected Criteria or(Criteria base, Criteria criteria) {
base.or(Arrays.asList(criteria.end())); base.or(Collections.singletonList(new Query(criteria)));
return base; return base;
} }
@ -122,7 +124,7 @@ class MongoQueryCreator extends AbstractQueryCreator<Query, Criteria> {
@Override @Override
protected Query complete(Criteria criteria, Sort sort) { protected Query complete(Criteria criteria, Sort sort) {
Query query = criteria.end(); Query query = new Query(criteria);
if (LOG.isDebugEnabled()) { if (LOG.isDebugEnabled()) {
LOG.debug("Created query " + query); LOG.debug("Created query " + query);

11
spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java

@ -15,6 +15,8 @@
*/ */
package org.springframework.data.document.mongodb.repository; package org.springframework.data.document.mongodb.repository;
import static org.springframework.data.document.mongodb.query.Criteria.where;
import java.io.Serializable; import java.io.Serializable;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -32,9 +34,6 @@ import org.springframework.data.repository.support.IsNewAware;
import org.springframework.data.repository.support.RepositorySupport; import org.springframework.data.repository.support.RepositorySupport;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import com.mongodb.QueryBuilder;
/** /**
* Repository base implementation for Mongo. * Repository base implementation for Mongo.
* *
@ -110,7 +109,7 @@ public class SimpleMongoRepository<T, ID extends Serializable> extends
List<T> result = List<T> result =
template.find( template.find(
new Query().start("_id").is(objectId).end(), new Query(where("_id").is(objectId)),
getDomainClass()); getDomainClass());
return result.isEmpty() ? null : result.get(0); return result.isEmpty() ? null : result.get(0);
} }
@ -161,8 +160,8 @@ public class SimpleMongoRepository<T, ID extends Serializable> extends
public void delete(T entity) { public void delete(T entity) {
Query query = Query query =
Query.startQueryWithCriteria(entityInformation.getFieldName()).is( new Query(where(entityInformation.getFieldName()).is(
entityInformation.getId(entity)).end(); entityInformation.getId(entity)));
template.remove(query); template.remove(query);
} }

11
spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateTests.java

@ -20,6 +20,8 @@ import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.endsWith; import static org.hamcrest.Matchers.endsWith;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
import static org.springframework.data.document.mongodb.query.Criteria.where;
import java.util.List; import java.util.List;
import org.junit.Before; import org.junit.Before;
@ -29,6 +31,7 @@ import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.document.mongodb.query.Criteria;
import org.springframework.data.document.mongodb.query.Query; import org.springframework.data.document.mongodb.query.Query;
import org.springframework.data.document.mongodb.query.Update; import org.springframework.data.document.mongodb.query.Update;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
@ -66,7 +69,7 @@ public class MongoTemplateTests {
MongoConverter converter = template.getConverter(); MongoConverter converter = template.getConverter();
List<Person> result = template.find(Query.startQueryWithCriteria("_id").is(converter.convertObjectId(person.getId())).end(), Person.class); List<Person> result = template.find(new Query(Criteria.where("_id").is(converter.convertObjectId(person.getId()))), Person.class);
assertThat(result.size(), is(1)); assertThat(result.size(), is(1));
assertThat(result, hasItem(person)); assertThat(result, hasItem(person));
} }
@ -81,8 +84,8 @@ public class MongoTemplateTests {
person.setAge(25); person.setAge(25);
mongoTemplate.insert(person); mongoTemplate.insert(person);
Query q = Query.startQueryWithCriteria("BOGUS").gt(22).end(); Query q = new Query(Criteria.where("BOGUS").gt(22));
Update u = Update.startUpdate().set("firstName", "Sven"); Update u = new Update().set("firstName", "Sven");
thrown.expect(DataIntegrityViolationException.class); thrown.expect(DataIntegrityViolationException.class);
thrown.expectMessage( endsWith("0 documents updated") ); thrown.expectMessage( endsWith("0 documents updated") );
mongoTemplate.updateFirst(q, u); mongoTemplate.updateFirst(q, u);
@ -91,7 +94,7 @@ public class MongoTemplateTests {
@Test @Test
public void simpleQuery() throws Exception { public void simpleQuery() throws Exception {
Query.startQueryWithCriteria("name").is("Mary").and("age").lt(33).gt(22).end().skip(22).limit(20); new Query(where("name").is("Mary")).and(where("age").lt(33).gt(22)).skip(22).limit(20);
// TODO: more tests // TODO: more tests
} }
} }

30
spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/builder/QueryTests.java → spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryTests.java

@ -13,7 +13,9 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.document.mongodb.builder; package org.springframework.data.document.mongodb.query;
import static org.springframework.data.document.mongodb.query.Criteria.where;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
@ -24,18 +26,14 @@ public class QueryTests {
@Test @Test
public void testSimpleQuery() { public void testSimpleQuery() {
Query q = new Query(); Query q = new Query(where("name").is("Thomas")).and(where("age").lt(80));
q.start("name").is("Thomas");
q.start("age").lt(80);
String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}"; String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}";
Assert.assertEquals(expected, q.getQueryObject().toString()); Assert.assertEquals(expected, q.getQueryObject().toString());
} }
@Test @Test
public void testQueryWithNot() { public void testQueryWithNot() {
Query q = new Query(); Query q = new Query(where("name").is("Thomas")).and(where("age").not().mod(10, 0));
q.start("name").is("Thomas");
q.start("age").not().mod(10, 0);
String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$not\" : { \"$mod\" : [ 10 , 0]}}}"; String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$not\" : { \"$mod\" : [ 10 , 0]}}}";
Assert.assertEquals(expected, q.getQueryObject().toString()); Assert.assertEquals(expected, q.getQueryObject().toString());
} }
@ -44,8 +42,8 @@ public class QueryTests {
public void testOrQuery() { public void testOrQuery() {
Query q = new Query();; Query q = new Query();;
q.or( q.or(
new Query().start("name").is("Sven").and("age").lt(50).end(), new Query(where("name").is("Sven")).and(where("age").lt(50)),
new Query().start("age").lt(50).end(), new Query(where("age").lt(50)),
new BasicQuery("{'name' : 'Thomas'}") new BasicQuery("{'name' : 'Thomas'}")
); );
String expected = "{ \"$or\" : [ { \"name\" : \"Sven\" , \"age\" : { \"$lt\" : 50}} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"; String expected = "{ \"$or\" : [ { \"name\" : \"Sven\" , \"age\" : { \"$lt\" : 50}} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}";
@ -54,8 +52,7 @@ public class QueryTests {
@Test @Test
public void testQueryWithLimit() { public void testQueryWithLimit() {
Query q = new Query(); Query q = new Query(where("name").gte("M").lte("T")).and(where("age").not().gt(22));
q.start("name").gte("M").lte("T").and("age").not().gt(22);
q.limit(50); q.limit(50);
String expected = "{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"; String expected = "{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}";
Assert.assertEquals(expected, q.getQueryObject().toString()); Assert.assertEquals(expected, q.getQueryObject().toString());
@ -64,8 +61,7 @@ public class QueryTests {
@Test @Test
public void testQueryWithFieldsAndSlice() { public void testQueryWithFieldsAndSlice() {
Query q = new Query(); Query q = new Query(where("name").gte("M").lte("T")).and(where("age").not().gt(22));
q.start("name").gte("M").lte("T").and("age").not().gt(22);
q.fields().exclude("address").include("name").slice("orders", 10); q.fields().exclude("address").include("name").slice("orders", 10);
String expected = "{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"; String expected = "{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}";
@ -73,4 +69,12 @@ public class QueryTests {
String expectedFields = "{ \"address\" : 0 , \"name\" : 1 , \"orders\" : { \"$slice\" : 10}}"; String expectedFields = "{ \"address\" : 0 , \"name\" : 1 , \"orders\" : { \"$slice\" : 10}}";
Assert.assertEquals(expectedFields, q.getFieldsObject().toString()); Assert.assertEquals(expectedFields, q.getFieldsObject().toString());
} }
@Test
public void testBasicQuery() {
Query q = new BasicQuery("{ \"name\" : \"Thomas\"}").and(where("age").lt(80));
String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}";
Assert.assertEquals(expected, q.getQueryObject().toString());
}
} }

2
spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/builder/SortTests.java → spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/SortTests.java

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.document.mongodb.builder; package org.springframework.data.document.mongodb.query;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;

17
spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/builder/UpdateTests.java → spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/UpdateTests.java

@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.document.mongodb.builder; package org.springframework.data.document.mongodb.query;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -21,7 +21,6 @@ import java.util.Map;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import org.springframework.data.document.mongodb.query.Update; import org.springframework.data.document.mongodb.query.Update;
import org.springframework.data.document.mongodb.query.Sort.Order;
public class UpdateTests { public class UpdateTests {
@ -121,4 +120,18 @@ public class UpdateTests {
Assert.assertEquals("{ \"$rename\" : { \"directory\" : \"folder\"}}", u.getUpdateObject().toString()); Assert.assertEquals("{ \"$rename\" : { \"directory\" : \"folder\"}}", u.getUpdateObject().toString());
} }
@Test
public void testBasicUpdateInc() {
Update u = new Update()
.inc("size", 1);
Assert.assertEquals("{ \"$inc\" : { \"size\" : 1}}", u.getUpdateObject().toString());
}
@Test
public void testBasicUpdateIncAndSet() {
Update u = new BasicUpdate("{ \"$inc\" : { \"size\" : 1}}")
.set("directory", "/Users/Test/Desktop");
Assert.assertEquals("{ \"$inc\" : { \"size\" : 1} , \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}",
u.getUpdateObject().toString());
}
} }
Loading…
Cancel
Save