Spring framework and MongoDB

In the previous tutorial, I introduced to you all the basic operations with MongoDB using Java. If your application is using Spring framework, make use of a Spring library for MongoDB to manipulate this database system. How is it in details? Let’s find out in this tutorial!

First, I will create a new Maven project as an example:

Spring framework and MongoDB

The library mentioned above is called spring-data-mongodb. I will add its dependency as follows:

The main interface for manipulating MongoDB in the spring-data-mongodb library is the MongoOperations interface. It defines many different ways that we can easily manipulate MongoDB. The main class implements the MongoOperations interface named MongoTemplate, and to use the MongoOperations interface, we need to declare the bean for the MongoTemplate class in the Spring container.

I will create a configuration file for Spring located in src/main/resources named spring.xml with the following content:

Class MongoTemplate has 3 constructors, see here for more! You can choose any constructor to initialize object for MongoTemplate. Here, I will initialize the MongoTemplate with a MongoClient object with the database name: MongoTemplate(com.mongodb.MongoClient mongoClient, String databaseName).

We need to initialize the bean for the MongoClient object.

If your MongoDB does not need a username, password then you can initialize the MongoClient object as follows:

in case your MongoDB installs locally and uses its default port.

In case MongoDB is installed on another machine, you can initialize the MongoClient object as follows:

If your MongoDB needs username and password then you can use the constructor MongoClient(ServerAddress addr, List<MongoCredential> credentialsList) to initialize it:

In the example of this tutorial, I installed MongoDB locally and did not need a username or password, so I just initialized the MongoClient object as follows:

Here we have finished configuring to work with MongoDB in Spring. Now let’s take an example!

I have a Student object as follows:

Insert a document:

Result:

Spring framework and MongoDB

Add Comment