Execution Callbacks

One common design feature of all Spring template classes is that all functionality is routed into one of the template’s execute callback methods. Doing so helps to ensure that exceptions and any resource management that may be required are performed consistently. While JDBC and JMS need this feature much more than MongoDB does, it still offers a single spot for exception translation and logging to occur. Consequently, using these execute callbacks is the preferred way to access the MongoDB driver’s MongoDatabase and MongoCollection objects to perform uncommon operations that were not exposed as methods on MongoTemplate.

The following list describes the execute callback methods.

  • <T> T execute (Class<?> entityClass, CollectionCallback<T> action): Executes the given CollectionCallback for the entity collection of the specified class.

  • <T> T execute (String collectionName, CollectionCallback<T> action): Executes the given CollectionCallback on the collection of the given name.

  • <T> T execute (DbCallback<T> action): Executes a DbCallback translating any exceptions as necessary. Spring Data MongoDB provides support for the Aggregation Framework introduced to MongoDB in version 2.2.

  • <T> T execute (String collectionName, DbCallback<T> action): Executes a DbCallback on the collection of the given name translating any exceptions as necessary.

  • <T> T executeInSession (DbCallback<T> action): Executes the given DbCallback within the same connection to the database so as to ensure consistency in a write-heavy environment where you may read the data that you wrote.

The following example uses the CollectionCallback to return information about an index:

boolean hasIndex = template.execute("geolocation", new CollectionCallbackBoolean>() {
  public Boolean doInCollection(Venue.class, DBCollection collection) throws MongoException, DataAccessException {
    List<Document> indexes = collection.getIndexInfo();
    for (Document document : indexes) {
      if ("location_2d".equals(document.get("name"))) {
        return true;
      }
    }
    return false;
  }
});