diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java index 2dd85c7f4..8f7425ce5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java @@ -1513,19 +1513,32 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware { CursorPreparer preparer, DbObjectCallback objectCallback, String collectionName) { try { - DBCursor cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName)); - if (preparer != null) { - cursor = preparer.prepare(cursor); + DBCursor cursor = null; + + try { + + cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName)); + + if (preparer != null) { + cursor = preparer.prepare(cursor); + } + + List result = new ArrayList(); + + while (cursor.hasNext()) { + DBObject object = cursor.next(); + result.add(objectCallback.doWith(object)); + } + + return result; + + } finally { + + if (cursor != null) { + cursor.close(); + } } - - List result = new ArrayList(); - - for (DBObject object : cursor) { - result.add(objectCallback.doWith(object)); - } - - return result; } catch (RuntimeException e) { throw potentiallyConvertRuntimeException(e); } @@ -1535,15 +1548,27 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware { DocumentCallbackHandler callbackHandler, String collectionName) { try { - DBCursor cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName)); - if (preparer != null) { - cursor = preparer.prepare(cursor); + DBCursor cursor = null; + + try { + cursor = collectionCallback.doInCollection(getAndPrepareCollection(getDb(), collectionName)); + + if (preparer != null) { + cursor = preparer.prepare(cursor); + } + + while (cursor.hasNext()) { + DBObject dbobject = cursor.next(); + callbackHandler.processDocument(dbobject); + } + + } finally { + if (cursor != null) { + cursor.close(); + } } - for (DBObject dbobject : cursor) { - callbackHandler.processDocument(dbobject); - } } catch (RuntimeException e) { throw potentiallyConvertRuntimeException(e); }