Introduction
In recent years, MongoDB has gained popularity as the preferred No-SQL database for application developers. To get started, today I will show you how to connect to MongoDB using Spring Data for various kind of Maven Java Projects including how to connect to MongoDB Atlas.
Softwares / Tools
1. Spring Tool Suite 4
2. Apache Maven 3.x
3. MongoDB 4.2
Project Type
1. Simple Spring Project
First of all, create a Maven Java Project in STS. Inside the pom.xml, import the below dependencies.
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.0.3.RELEASE</version>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>3.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.1.0</version>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver-sync</artifactId>
<version>4.1.0</version>
</dependency>
Following is the snippet of Java class that connects to a local MongoDB and retrieves documents from a collection.
package programnplay
import java.util.List;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.client.MongoClients;
import org.springframework.data.mongodb.core.MongoTemplate;
import com.mongodb.client.MongoClients;
public class MongoApp {
public static void main(String[] args) {
MongoTemplate template = new MongoTemplate(MongoClients.create(), "myDatabase");
List<Person> list = template.findAll(Person.class);
public static void main(String[] args) {
MongoTemplate template = new MongoTemplate(MongoClients.create(), "myDatabase");
List<Person> list = template.findAll(Person.class);
System.out.println("Person list size is "+list.size());
list.forEach((person) -> System.out.println(person.getName()));
}
list.forEach((person) -> System.out.println(person.getName()));
}
}
class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here the collection is "Person" in database "myDatabase". Ensure this collection already exists with some data in your local MongoDB before you run the program. Sample collection is given below.
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5a"),
"name" : "Rajib"
"_id" : ObjectId("5f4cfd17e94de11cb3392d5a"),
"name" : "Rajib"
}
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5b"),
"name" : "Rahul"
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5b"),
"name" : "Rahul"
}
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5c"),
"name" : "Sachin"
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5c"),
"name" : "Sachin"
}
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5d"),
"name" : "Sourav"
}
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5e"),
"name" : "Laxman"
}
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5d"),
"name" : "Sourav"
}
{
"_id" : ObjectId("5f4cfd17e94de11cb3392d5e"),
"name" : "Laxman"
}
Mongoclients.create() establishes a local connection. Then we create an instance of MongoTemplate. Using this instance, we can fire MongoDB queries like insert, find, update etc. Below is given sample screenshot of output.
Output of Spring Application |
2. Simple Spring Project with Atlas
First of all, we need to create a Connection String in Atlas MongoDB. Follow the below steps.
- Log in to Atlas.
- Select 'Clusters' on left side menu.
- In the popup, select 'Connect your application'.
- Next popup, select driver as 'Java' and version as '4.1 or later'. Copy the connection string replaced with proper user name and password that will be used in Java application.
Now pass the Connection String in your program as below
MongoTemplate template = new MongoTemplate(MongoClients.create("mongodb+srv://<username>:<password>@<host>/?retryWrites=true&w=majority"), "myDatabase");
Rest of the code will remain same as previous program. You can checkout the code from here.
3. Spring Boot Project
Next we will connect to local MongoDB from a Spring Boot application. Create a Spring Starter Project in STS. In 'Project Dependencies' page, select 'Spring Data MongoDB'. Now STS will create a Spring Boot project with all required dependencies. Following is the sample of dependencies in your pom.xml file.
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Let us now write the main class.
package programnplay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootMongoApplication {
public static void main(String[] args) {
SpringApplication.run(BootMongoApplication.class, args);
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BootMongoApplication {
public static void main(String[] args) {
SpringApplication.run(BootMongoApplication.class, args);
}
}
Next we will create a controller class.
package programnplay;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import programnplay.repo.BootMongoRepository;
import programnplay.repo.Person;
@RestController
public class BootMongoController {
@Autowired
BootMongoRepository repository;
@GetMapping("/getPersons")
public List<Person> getPersons(){
return repository.findAll();
}
}
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import programnplay.repo.BootMongoRepository;
import programnplay.repo.Person;
@RestController
public class BootMongoController {
@Autowired
BootMongoRepository repository;
@GetMapping("/getPersons")
public List<Person> getPersons(){
return repository.findAll();
}
}
We have autowired an instance of BootMongoRepository which is defined below.
package programnplay.repo;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface BootMongoRepository extends MongoRepository<Person, String> {
}
import org.springframework.data.mongodb.repository.MongoRepository;
public interface BootMongoRepository extends MongoRepository<Person, String> {
}
This interface extends MongoRepository which is a Spting Data MongoDB interface that provides us all common functionalities to work with a MongoDB collection. Here our collection is Person. Model class that maps to this collection is given below.
package programnplay.repo;
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
As last step, we only need to specify the database in application.properties file which is under src/main/resources folder.
spring.data.mongodb.database=myDatabase
Now run the main class as Spring Boot App. Hit the url 'http://localhost:8080/getPersons' in one of your favorite browsers. You will get output as shown below.
4. Spring Boot Project with Atlas
If you are developing a Spring Boot project that connects to Atlas MongoDB, then you just need to modify application.properties file as below. You have to use Connection String for your Atlas. For creating Connection String, follow the same procedure as described few steps back.
spring.data.mongodb.uri=mongodb+srv://<username>:<password>@<host>/<database>?retryWrites=true&w=majority
Rest of the code will remain same as specified for the previous Spring Boot project. You can checkout the code from here.
Any comment on the blog, let me know it in comment section below. Hope year 2021 brings a new dawn. Stay safe, stay happy.
No comments:
Post a Comment