Using Spring Data with MongoDB

Spring Data repositories are an abstraction that implement a data access layer over the underlying datastore. Spring Data repositories reduce the boilerplate code required to access a datastore. Spring Data repositories may be used with MongoDB data store.

To enable the Spring Data repositories infrastructure for MongoDB annotate the JavaConfig class with @EnableMongoRepositories. Annotate the JavaConfig class SpringMongoApplicationConfig class with @EnableMongoRepositories(“com.mongo.repositories”). The com.mongo.repositories is the package to search for repositories. Specify the packages to scan for annotated components using the @ComponentScan annotation with the basePackageClasses element set to the service class CatalogService.class, which we shall develop later in this section. The package of each class specified in basePackageClasses is scanned. The modified class declaration for the SpringMongoApplicationConfig class is as follows.

@Configuration

@EnableMongoRepositories(“com.mongo.repositories”)

@ComponentScan(basePackageClasses = {CatalogService.class})

public class SpringMongoApplicationConfig extends AbstractMongoConfiguration {

}

The central repository marker interface is org.springframework.data.repository.Repository, and it provides CRUD access on top of the entities. The entity class Catalog is defined earlier in the chapter. The generic interface for CRUD operations on a repository is org.springframework.data. repository.CrudRepository. The MongoDB server specific repository interface is org.springframework. data.mongodb.repository. MongoRepository<T,ID extends Serializable>, which extends the CrudRepository interface. The interface is parameterized over the domain type, which would be Catalog for the example, and ID type, which is String in the example. The ID extends the java.io.Serializable interface to be able to serialize the ID in the MongoDB server. Create an interface, CatalogRepository, which extends the parameterized type MongoRepository<Catalog, String>. The CatalogRepository represents the MongoDB specific repository interface to store entities of type Catalog and with Id of type String in MongoDB server.

package com.mongo.repositories;

import org.springframework.data.mongodb.repository.MongoRepository; import com.mongo.model.Catalog;

public interface CatalogRepository extends MongoRepository<Catalog, String> {

}

Create a service class CatalogService in which to access the repository instance from the context as follows.

ApplicationContext context = new AnnotationConfigApplicationContext(

SpringMongoApplicationConfig.class);

CatalogRepository repository = context.getBean(CatalogRepository.class);

Subsequently, perform CRUD operations on the MongoDB document store using the CatalogRepository instance, which is declared as a class variable. Add the following (Table 10-17) methods to the CatalogService class for the CRUD operations. The methods names are same or similar to the MongoRepository methods’ names.

Add method invocations for each of the methods in the main method. To run the CatalogService class right-click on the CatalogService.java application in the Package Explorer and select Run As ➤ Java Application as shown in Figure 10-22.

We shall invoke each method separately and comment out the other methods when the CatalogService.java application is run.

1. Getting Document Count

The MongoRepository<T,ID extends Serializable> interface, which extends the CrudRepository<T,ID> interface and provides CRUD operation methods. The MongoRepository interface also includes a count() method, which returns the number of entities stored in a collection. To be able to count entities, first create some entities using the MongoOperations instance as discussed earlier in the chapter. Run the App application to invoke the addDocumentBatch() method to add some documents. Invoke the count() method using the CatalogRepository instance and output the long value returned.

public static void count() {

System.out.println(“Number of documents: ” + repository.count());

}

The output in the Eclipse Console in Figure 10-23 shows that the number of document entities stored is 2.

2. Finding Entities from Repository

The MongoRepository interface provides the following (Table 10-18) methods for finding documents from repository.

Before running the CatalogService application to find documents, do drop the catalog collection as we shall find the documents already in the catalog collection.

2.1. Finding All Documents

To be able to find documents first create some entities using the MongoOperations instance as discussed earlier in the chapter. As an example, find all instances from the CatalogRepository instance repository using the findAll() method.

Iterable<Catalog> iterable = repository.findAll();

The findAll() method returns an Iterable from which obtain an Iterator using the iterator() method.

Iterator<Catalog> iter = iterable.iterator();

Iterate over the entity instances using the Iterator and output the fields for each entity instance.

The findAll() method is as follows.

public static void findAll() {

Iterable<Catalog> iterable = repository.findAll();

Iterator<Catalog> iter = iterable.iterator(); while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal: ” + catalog.getJournal());

System.out.println(“Publisher: ” + catalog.getPublisher());

System.out.println(“Edition: ” + catalog.getEdition());

System.out.println(“Title: ” + catalog.getTitle());

System.out.println(“Author: ” + catalog.getAuthor());

}

}

When the CatalogService application is run the field values for the two entity instances are output in the Eclipse Console as shown in Figure 10-24.

2.2. Finding One Document

As an example of using the findOne() method in MongoRepository, find the entity instance for a specific id, which is known to be in the MongoDB database. Subsequently output the field values for the entity instance. The findOne() method in the CatalogService class is as follows.

public static void findOne(String id) {

Catalog catalog = repository.findOne(id);

System.out.println(“Journal: ” + catalog.getJournal());

System.out.println(“Publisher: ” + catalog.getPublisher());

System.out.println(“Edition: ” + catalog.getEdition());

System.out.println(“Title: ” + catalog.getTitle());

System.out.println(“Author: ” + catalog.getAuthor());

}

Invoke the findOne() method from the main method using a specific id, which was save earlier.

if (repository.exists(“53ea75e336845ce83eeb214f”)) {

findOne(“53ea75e336845ce83eeb214f”);

}

The field values for the entity instance are output in the Eclipse Console as shown in Figure 10-25.

3. Saving Entities

The MongoRepository interface provides the following methods (Table 10-19) for saving documents using the repository.

3.1. Saving a Single Document

As an example, create and save an entity instance using the save(S entity) method.

  1. In the save() method in the CatalogService class create a Catalog instance. The id field argument may be an empty String as the _id field is generated automatically.
  1. Subsequently, invoke the save() method using the Catalog instance as method argument. To find the saved documents invoke the findAll() method in CatalogService. The save() method in CatalogService is as follows.

public static void save() {

Catalog catalog = new Catalog(“”, “Oracle Magazine”,

“Oracle Publishing”, “11-12-2013”, “Engineering as a Service”,

“Kelly, David”);

repository.save(catalog);

findAll();

}

  1. Invoke the save() method from the main method to save a Catalog instance and subsequently find and list the document’s field values as shown in Figure 10-26.

3.2. Saving a Batch of Documents

As an example of using the save(Iterable<S> entities) method, create an ArrayList of entity instances in the saveBatch() method in CatalogService application. Invoke the save(Iterable<S> entities) method with the ArrayList instance as an argument.

repository.save(arrayList);

Subsequently invoke the findAll() method to find all the saved entities. The saveBatch() method is as follows.

public static void saveBatch() {

Catalog catalog1 = new Catalog(‘”‘, “Oracle Magazine”,

“Oracle Publishing”, “11-12-2013”, “Engineering as a Service”,

“Kelly, David”);

Catalog catalog2 = new Catalog(“”, “Oracle Magazine”,

“Oracle Publishing”, “11-12-2013”,

“Quintessential and Collaborative”, “Haunert, Tom”);

entities = new ArrayList<Catalog>();

entities.add(catalogl);

entities.add(catalog2);

repository.save(entities);

findAll();

}

Invoke the saveBatch() method from the main method. Before running the CatalogService application drop the previously created catalog collection using the db.catalog.drop() method in the Mongo shell. When the CatalogService application is run the collection of entity instances in the ArrayList get added to the MongoDB server. The saved Catalog entity field values get output to the Eclipse Console as shown in Figure 10-27.

3.3. Deleting Entities

The MongoRepository interface provides the following (Table 10-20) methods for deleting documents using the repository.

4. Deleting a Document By Id

As an example of using the delete(ID id) method delete the entity with a known ID that is in the MongoDB server in the deleteById() method in CatalogService application.

First, save some documents in the deleteById() method. Use class variables catalog1 and catalog2 for the Catalog entities saved. In the deleteById() method invoke the delete(ID id) method of the CatalogRepository instance with the Id for one of the saved documents as method argument. The id for a document is obtained using the getId() method. Subsequently invoke the findAll() method to find all document.

public static void deleteById() {

//Add documents

repository.delete(catalog1.getId());

findAll();

}

In the main method of CatalogService invoke the deleteById() method.

deleteById();

When the CatalogService application is run the Catalog instance for the specified Id gets deleted.

The subsequent call to findAll() lists only one of the saved documents as shown in Figure 10-28.

5. Deleting All Documents

As an example of using the deleteAll() method, first add a batch of documents in the deleteAll() method in CatalogService. Subsequently invoke the deleteAll() method of the CatalogRepository instance. Subsequently invoke the findAll() method to find all the documents.

public static void deleteAll() {

//Add documents

repository.deleteAll();

findAll();

}

In the main method of CatalogService invoke the deleteAll() method.

deleteAll();

When the CatalogService application is run a batch of documents are saved and subsequently the deleteAll() method deletes all the documents saved. The subsequent invocation of the findAll() method does not find and list any documents as all documents have been deleted as shown in Figure 10-29.

The CatalogService class is listed:

package com.mongo.service;

import java.util.ArrayList; import java.util.Iterator;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.mongo.config.SpringMongoApplicationConfig;

import com.mongo.model.Catalog;

import com.mongo.repositories.CatalogRepository;

public class CatalogService {

public static CatalogRepository repository;

public static ArrayList<Catalog> entities;

public static Catalog catalogl; public static Catalog catalog2;

public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(

SpringMongoApplicationConfig.class);

repository = context.getBean(CatalogRepository.class);

// saveBatch();

// count();

// findAll();

// saveBatch();

// deleteAll();

// deleteById();

/*

* if (repository.exists(“55cb4f50db9499f5a242ad93”)) {

* findOne(“55cb4f50db9499f5a242ad93”); }

*/

// save();

// saveBatch();

// deleteById(); deleteAll();

}

public static void deleteAll() {

catalog1 = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Engineering as a Service”, “Kelly, David”);

catalog2 = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Quintessential and Collaborative”,

“Haunert, Tom”);

entities = new ArrayList<Catalog>();

entities.add(catalog1);

entities.add(catalog2);

repository.save(entities);

repository.deleteAll();

findAll();

}

public static void deleteById() {

catalog1 = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Engineering as a Service”, “Kelly, David”);

catalog2 = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Quintessential and Collaborative”,

“Haunert, Tom”);

entities = new ArrayList<Catalog>();

entities.add(catalogl);

entities.add(catalog2);

repository.save(entities);

repository.delete(catalog1.getId());

findAll();

}

public static void saveBatch() {

catalog1 = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Engineering as a Service”, “Kelly, David”);

catalog2 = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Quintessential and Collaborative”,

“Haunert, Tom”);

entities = new ArrayList<Catalog>();

entities.add(catalog1);

entities.add(catalog2);

repository.save(entities);

findAll();

}

public static void save() {

Catalog catalog = new Catalog(“”, “Oracle Magazine”, “Oracle Publishing”,

“11-12-2013”, “Engineering as a Service”, “Kelly, David”);

repository.save(catalog); findAll();

}

public static void findOne(String id) {

Catalog catalog = repository.findOne(id);

System.out.println(“Journal: ” + catalog.getJournal());

System.out.println(“Publisher: ” + catalog.getPublisher());

System.out.println(“Edition: ” + catalog.getEdition());

System.out.println(“Title: ” + catalog.getTitle());

System.out.println(“Author: ” + catalog.getAuthor());

}

public static void count() {

System.out.println(“Number of documents: ” + repository.count());

}

public static void findAll() {

Iterable<Catalog> iterable = repository.findAll();

Iterator<Catalog> iter = iterable.iterator();

while (iter.hasNext()) {

Catalog catalog = iter.next();

System.out.println(“Journal: ” + catalog.getJournal());

System.out.println(“Publisher: ” + catalog.getPublisher());

System.out.println(“Edition: ” + catalog.getEdition());

System.out.println(“Title: ” + catalog.getTitle());

System.out.println(“Author: ” + catalog.getAuthor());

}

}

}

Source: Vohra Deepak (2015), Pro MongoDB™ Development, Apress; 1st ed. edition.

Leave a Reply

Your email address will not be published. Required fields are marked *