springboot-SpringBoot 2 and mongotemplate CRUD example
-SpringBoot 2 and mongodb CRUD example using MongoRepository
1. Introduction
This article would demo how to use SpringBoot’s mongotemplate to do simple CRUD(create-read-update-delete) operations on MongoDB.
2. Environments
- SpringBoot 2.x
- MongoDB
- jdk 1.8
3. The example
3.1 Define dependency in your pom
Add spring data mongodb to your pom like this:
<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.0.2.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
3.2 Define your domain class
Let’s define a domain class that would map to MongoDB document like this:
package hello.mongo.domain;
public class Person {
private int id;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
3.3 Define your MongoDB Config class
We should define a config class to access MongoDB.
package hello.mongo.dao;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.core.MongoTemplate;
@Configuration
public class MongoConfig extends AbstractMongoConfiguration {
@Value("${spring.data.mongodb.database}")
private String databaseName;
@Value("${spring.data.mongodb.host}")
private String host;
@Value("${spring.data.mongodb.port}")
private int port;
public @Bean MongoClient mongoClient() {
return new MongoClient(host,port);
}
public @Bean
MongoTemplate mongoTemplate() throws Exception {
MongoTemplate template = new MongoTemplate(mongoDbFactory(), mappingMongoConverter());
template.setWriteResultChecking(WriteResultChecking.EXCEPTION);
return template;
}
@Override
protected String getDatabaseName() {
return databaseName;
}
}
It’s very simple:
- It’s a @Configuration class which indicates this class has some bean definitions.
- It extends the AbstractMongoConfiguration to extend and do some customizations on MongoDB configurations.
- It uses @Value annotation to read MongoDB configrations from application.properties
- The most important is that this class return a MongoTemplate class to be used to access MongoDB
3.4 Configure by application.properties
#mongodb
spring.data.mongodb.host=1.1.1.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=TEST_DB
#logging
logging.level.org.springframework.data=debug
logging.level.=error
3.5 Write a CommandLineRunner to test your code
package hello.mongo.commands;
import hello.mongo.domain.Person;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Component;
import java.util.List;
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;
@Component
public class MyMongoTemplateCommand implements CommandLineRunner {
private static Logger logger = LoggerFactory.getLogger(MyMongoTemplateCommand.class);
@Autowired
private MongoOperations mongoOperations;
@Override
public void run(String... strings) throws Exception {
if(mongoOperations!=null) {
Person p = new Person("Joe", 34);
// Insert is used to initially store the object into the database.
mongoOperations.insert(p);
logger.info("Insert: " + p);
// Find
p = mongoOperations.findById(p.getId(), Person.class);
logger.info("Found: " + p);
// Update
mongoOperations.updateFirst(query(where("name").is("Joe")), update("age", 35), Person.class);
p = mongoOperations.findOne(query(where("name").is("Joe")), Person.class);
logger.info("Updated: " + p);
// Delete
mongoOperations.remove(p);
// Check that deletion worked
List<Person> people = mongoOperations.findAll(Person.class);
logger.info("Number of people = : " + people.size());
mongoOperations.dropCollection(Person.class);
}
}
}
4. Summary
You can see that spring data mongotemplate makes the mongodb operations more simpler.