From 6287fa425d815609711c17b80bc9546576ae65b8 Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Wed, 18 May 2011 23:16:31 +0200 Subject: [PATCH] =?UTF-8?q?DATADOC-108=20-=20added=20findbyId(=E2=80=A6)?= =?UTF-8?q?=20methods=20to=20MongoTemplate.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Removed Criteria.whereId(…). Updated SimpleMongoRepository to use the new method and use more core template methods to prevent objects from being marshalled to find out whether a particular object exists. --- .../document/mongodb/MongoOperations.java | 22 +++++++++++++++++ .../data/document/mongodb/MongoTemplate.java | 21 ++++++++++++++-- .../data/document/mongodb/query/Criteria.java | 4 ---- .../repository/SimpleMongoRepository.java | 24 ++++++++++++------- .../mongodb/MongoTemplateMappingTests.java | 15 +++--------- .../data/document/mongodb/PersonExample.java | 17 ++++--------- 6 files changed, 64 insertions(+), 39 deletions(-) diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java index cf8b9f1ed..c26fcbeaf 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java @@ -332,6 +332,28 @@ public interface MongoOperations { */ List find(String collectionName, Query query, Class targetClass, CursorPreparer preparer); + /** + * Returns a document with the given id mapped onto the given class. The collection the query is ran against will be + * derived from the given target class as well. + * + * @param + * @param id the id of the document to return. + * @param targetClass the type the document shall be converted into. + * @return the document with the given id mapped onto the given target class. + */ + T findById(Object id, Class targetClass); + + /** + * Returns the document with the given id from the given collection mapped onto the given target class. + * + * @param + * @param collectionName the collection to query for the document + * @param id the id of the document to return + * @param targetClass the type to convert the document to + * @return + */ + T findById(String collectionName, Object id, Class targetClass); + /** * Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the * specified type. The first document that matches the query is returned and also removed from the collection in the diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java index d70b04d49..44ed454ad 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java @@ -392,6 +392,18 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher public List find(String collectionName, Query query, Class targetClass, CursorPreparer preparer) { return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, preparer); } + + public T findById(Object id, Class targetClass) { + MongoPersistentEntity persistentEntity = mappingContext.getPersistentEntity(targetClass); + return findById(persistentEntity.getCollection(), id, targetClass); + } + + public T findById(String collectionName, Object id, Class targetClass) { + MongoPersistentEntity persistentEntity = mappingContext.getPersistentEntity(targetClass); + MongoPersistentProperty idProperty = persistentEntity.getIdProperty(); + String idKey = idProperty == null ? ID : idProperty.getName(); + return doFindOne(collectionName, new BasicDBObject(idKey, id), null, targetClass); + } // Find methods that take a Query to express the query and that return a single object that is // also removed from the collection in the database. @@ -724,8 +736,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher } public void remove(Object object) { - Object idValue = this.getIdValue(object); - remove(new Query(whereId().is(idValue)), object.getClass()); + remove(new Query(where(getIdPropertyName(object)).is(getIdValue(object))), object.getClass()); } public void remove(Query query, Class targetClass) { @@ -959,6 +970,12 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher throw new MappingException(e.getMessage(), e); } } + + protected String getIdPropertyName(Object object) { + MongoPersistentEntity persistentEntity = mappingContext.getPersistentEntity(object.getClass()); + MongoPersistentProperty idProperty = persistentEntity.getIdProperty(); + return idProperty == null ? ID : idProperty.getName(); + } /** * Populates the id property of the saved object, if it's not set already. diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java index 698bdf2fb..cf2f4df0c 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java @@ -66,10 +66,6 @@ public class Criteria implements CriteriaDefinition { return new Criteria(key); } - public static Criteria whereId() { - return new Criteria("id"); - } - /** * Static factory method to create a Criteria using the provided key * diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java index ea1bc3d9f..a3b01bcf7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java @@ -22,6 +22,8 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import org.springframework.dao.DataAccessException; +import org.springframework.data.document.mongodb.CollectionCallback; import org.springframework.data.document.mongodb.MongoOperations; import org.springframework.data.document.mongodb.MongoTemplate; import org.springframework.data.document.mongodb.query.Criteria; @@ -33,6 +35,10 @@ import org.springframework.data.domain.Sort; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.util.Assert; +import com.mongodb.BasicDBObject; +import com.mongodb.DBCollection; +import com.mongodb.MongoException; + /** * Repository base implementation for Mongo. * @@ -95,8 +101,7 @@ public class SimpleMongoRepository implements Paging * ) */ public T findOne(ID id) { - - return template.findOne(entityInformation.getCollectionName(), getIdQuery(id), entityInformation.getJavaType()); + return template.findById(id, entityInformation.getJavaType()); } private Query getIdQuery(Object id) { @@ -114,9 +119,14 @@ public class SimpleMongoRepository implements Paging * org.springframework.data.repository.Repository#exists(java.io.Serializable * ) */ - public boolean exists(ID id) { + public boolean exists(final ID id) { + + return template.execute(entityInformation.getCollectionName(), new CollectionCallback() { - return findOne(id) != null; + public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException { + return collection.count(new BasicDBObject("_id", id)) > 0; + } + }); } /* @@ -134,7 +144,7 @@ public class SimpleMongoRepository implements Paging * @see org.springframework.data.repository.Repository#delete(java.io.Serializable) */ public void delete(ID id) { - delete(findOne(id)); + template.remove(entityInformation.getCollectionName(), getIdQuery(id), entityInformation.getJavaType()); } /* @@ -144,9 +154,7 @@ public class SimpleMongoRepository implements Paging * org.springframework.data.repository.Repository#delete(java.lang.Object) */ public void delete(T entity) { - - template.remove(entityInformation.getCollectionName(), getIdQuery(entityInformation.getId(entity)), - entity.getClass()); + delete(entityInformation.getId(entity)); } /* diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java index 7f34354a6..b58891fd3 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java @@ -15,12 +15,9 @@ */ package org.springframework.data.document.mongodb; -import static org.hamcrest.Matchers.hasItem; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; -import java.util.List; - import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -29,9 +26,6 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.dao.DataAccessException; -import org.springframework.data.document.mongodb.convert.MongoConverter; -import org.springframework.data.document.mongodb.query.Criteria; -import org.springframework.data.document.mongodb.query.Query; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -98,11 +92,9 @@ public class MongoTemplateMappingTests { person.setAge(25); template.insert(person); - List result = template.find(new Query(Criteria.where("_id").is(person.getId())), Person.class); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(person)); - assertThat(result.get(0).getFirstName(), is("Oliver")); - assertThat(result.get(0).getAge(), is(25)); + Person result = template.findById(person.getId(), Person.class); + assertThat(result.getFirstName(), is("Oliver")); + assertThat(result.getAge(), is(25)); } private void checkPersonPersisted(MongoTemplate template) { @@ -114,5 +106,4 @@ public class MongoTemplateMappingTests { } }); } - } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java index b728aeef6..096f0b753 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java @@ -15,7 +15,6 @@ */ package org.springframework.data.document.mongodb; -import java.util.Iterator; import java.util.List; import org.apache.commons.logging.Log; @@ -24,12 +23,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import static org.springframework.data.document.mongodb.query.Criteria.*; -import org.springframework.data.document.mongodb.query.Query; -import static org.springframework.data.document.mongodb.query.Query.query; -import org.springframework.data.document.mongodb.query.Update; -import static org.springframework.data.document.mongodb.query.Update.update; - public class PersonExample { private static final Log log = LogFactory.getLog(PersonExample.class); @@ -59,7 +52,7 @@ public class PersonExample { log.debug("Saved: " + p); - p = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); + p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); log.debug("Found: " + p); @@ -67,15 +60,13 @@ public class PersonExample { // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), update("age", 24)); - p = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); + p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); log.debug("Updated: " + p); List folks = mongoOps.getCollection(PersonWithIdPropertyOfTypeString.class); log.debug("Querying for all people..."); - for (Iterator iterator = folks.iterator(); iterator.hasNext();) { - PersonWithIdPropertyOfTypeString personWithIdPropertyOfTypeString = (PersonWithIdPropertyOfTypeString) iterator - .next(); - log.debug(personWithIdPropertyOfTypeString); + for (PersonWithIdPropertyOfTypeString element : folks) { + log.debug(element); } // mongoOps.remove( query(whereId().is(p.getId())), p.getClass());