1 introduction
Springboot is the easiest way to use Spring, and MongoDB is the most popular NoSQL database. Both of them are highly used in distributed and micro-service architecture. This paper will introduce how to integrate MongoDB in Springboot with examples: MongoRepository and MongoTemplate.
The code structure is as follows:
2 Project Preparation
2.1 Starting the MongoDB Instance
For convenience, use Docker to start MongoDB, detailed guidance document please refer to: use Docker to install a MongoDB latest version of play, here no further details.
2.2 Introducing dependencies
The main dependencies are Web and MongoDB starter. Add the following code to pom.xml:
<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>Copy the code
2.3 Configuring Database Connection Information
As with MySQL or Oracle, MongoDB also needs to configure connection information, as shown in application.properties:
server.port=8080
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.database=testdb
spring.data.mongodb.username=user
spring.data.mongodb.password=123456
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017Copy the code
2.4 Create data model entities
Create User class as follows:
package com.pkslow.mongo.model; import org.springframework.data.annotation.Id; import java.util.Date; public class User { @Id private String userId; private String name; private Integer age; private Date createTime = new Date(); public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; }}Copy the code
There is no need to create a corresponding Collections (table) in MongoDB, which will be created automatically when new Collections are added via the Web application.
3 Method 1: MongoRepository
3.1 Define the data access layer UserRepository
As anyone who has used Spring Jpa knows, Repository is actually a class for manipulating databases. The same is true in the integration of the non-relational MongoDB database. Spring will help us implement the corresponding interface method, developers do not even need to write SQL, very easy. The code is as follows:
package com.pkslow.mongo.dal;
import com.pkslow.mongo.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}Copy the code
MongoRepository: MongoRepository:
3.2 implement the Controller
Controller is more basic, I will not explain, common annotations are necessary to master, directly on the code:
package com.pkslow.mongo.contrlloer; import com.pkslow.mongo.dal.UserRepository; import com.pkslow.mongo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/user") public class UserController { @Autowired private final UserRepository userRepository; public UserController(UserRepository userRepository) { this.userRepository = userRepository; } @GetMapping("") public List<User> getAllUsers() { return userRepository.findAll(); } @GetMapping("/{userId}") public User getByUserId(@PathVariable String userId) { return userRepository.findById(userId).orElse(new User()); } @PostMapping("") public User addNewUser(@RequestBody User user) { return userRepository.save(user); } @DeleteMapping("/{userId}") public String delete(@PathVariable String userId) { User user = new User(); user.setUserId(userId); userRepository.deleteById(userId); return "deleted: " + userId; } @PutMapping("") public User update(@RequestBody User user) { return userRepository.save(user); }}Copy the code
Note that the code does not handle exceptions, so I’ll leave them out for a quick demonstration.
3.3 test
After the Postman test, each interface is successfully invoked. I’m not going to do a screenshot.
MongoTemplate mode 2: MongoTemplate
4.1 Define the data access layer UserDAL
Define the interface as:
package com.pkslow.mongo.dal;
import com.pkslow.mongo.model.User;
import java.util.List;
public interface UserDAL {
List<User> findAll();
User findById(String userId);
User save(User user);
void deleteById(String userId);
}Copy the code
Then implement the interface as follows:
package com.pkslow.mongo.dal; import com.pkslow.mongo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class UserDALImpl implements UserDAL { @Autowired private MongoTemplate template; @Override public List<User> findAll() { return template.findAll(User.class); } @Override public User findById(String userId) { return template.findById(userId,User.class); } @Override public User save(User user) { return template.save(user); } @Override public void deleteById(String userId) { Query query = new Query(); query.addCriteria(Criteria.where("userId").is(userId)); template.remove(query, User.class); }}Copy the code
4.2 Implement another Controller
The code of this Controller is basically the same as before, except for the data access class. The code is as follows:
package com.pkslow.mongo.contrlloer; import com.pkslow.mongo.dal.UserDAL; import com.pkslow.mongo.model.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/userTemplate") public class UserTemplateController { @Autowired private final UserDAL userDAL; public UserTemplateController(UserDAL userDAL) { this.userDAL = userDAL; } @GetMapping("") public List<User> getAllUsers() { return userDAL.findAll(); } @GetMapping("/{userId}") public User getByUserId(@PathVariable String userId) { return userDAL.findById(userId); } @PostMapping("") public User addNewUser(@RequestBody User user) { return userDAL.save(user); } @DeleteMapping("/{userId}") public String delete(@PathVariable String userId) { User user = new User(); user.setUserId(userId); userDAL.deleteById(userId); return "deleted: " + userId; } @PutMapping("") public User update(@RequestBody User user) { return userDAL.save(user); }}Copy the code
4.3 test
The tests, too, all passed:
5 concludes
This article explains how to integrate Springboot and MongoDB through examples. There are two main methods: MongoRepository and MongoTemplate. The code has been posted in this article. If it is not clear, you can reply
to get the code.
Visit pumpkin Talk www.pkslow.com for more exciting articles!
Welcome to pay attention to the wechat public number “Pumpkin slow Talk”, will continue to update for you…
Read more and share more; Write more. Organize more.