MongoDB is the most popular NoSQL database, and SpringBoot is a best practice for using Spring. Today, we will talk about two ways to integrate SpringBoot with MongoDB. The installation of MongoDB can be found on the official website. The most convenient way for local development is to use Docker.
First, preparation
1. Project generation
Same old rules, usestart.spring.io/Select the JAR package we want to rely on, generate a demo, and import it into Idea
2. Configuration items
In the application.properties file, configure the MongoDB address
spring.data.mongodb.database=springmongo spring.data.mongodb.username=springmongo spring.data.mongodb.password=springmongo spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 # Also this way, can according to be fond of to configure # spring. The data. The mongo. Uri = mongo: : / / springmongo springmongo @ localhost: 27017 / springmongoCopy the code
Use MongoTemplate
Create entity UserInfo
import lombok.Data; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; /** * @author Programmer Niu * @id is a Spring annotation, @data @document public class UserInfo {@id private String userId; private String userName; private Integer age; private String address; }Copy the code
@Document is similar to @Entity in that it is an Entity and @Id is a primary key
Other Spring Data mongoDB annotations include:
@Document
To declare a Java class as a mongodb document, specify the corresponding document for that class with the Collection parameter. @document (Document =”mongodb for collection name “)
@Id
The unique identity of the document, ObjectId in mongodb, is unique
@Indexed
This field requires an index. Creating an index can greatly improve query efficiency.
@CompoundIndex
Compound index declaration, building compound index can effectively improve the efficiency of multi-field query.
@Field
Alias the fields that are mapped to mongodb
@Dbref
The identity refers to another document, which may be in a different database
@Version
Identify change properties as versioning
@Transient
By default, all private fields are mapped to the document, and the field identified by this annotation is excluded from the field column stored in the database (that is, the field is not saved to mongodb).
2. Define interfaces
/ * * *@authorPublic - public - number: a Niu programmer */
public interface UserInfoDAO {
public UserInfo save(UserInfo userInfo);
public UserInfo getUser(String userId);
}
Copy the code
3. Interface implementation
/ * * *@authorPublic - public - number: a Niu programmer */
@Repository
public class UserInfoDaoImpl implements UserInfoDAO {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public UserInfo save(UserInfo userInfo) {
return mongoTemplate.save(userInfo);
}
@Override
public UserInfo getUser(String userId) {
UserInfo userInfo = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(userId)),UserInfo.class);
returnuserInfo; }}Copy the code
4. Define the call controller
/ * * *@authorPublic - public - number: a Niu programmer */
@RestController
public class UserInfoController {
@Autowired
private UserInfoDAO userInfoDAO;
@RequestMapping("/getUser/{userId}")
public UserInfo getUserInfo(@PathVariable("userId")String userId){
return userInfoDAO.getUser(userId);
}
@PostMapping("/addUser")
public UserInfo addUserInfo(@RequestBody UserInfo userInfo){
returnuserInfoDAO.save(userInfo); }}Copy the code
5, the results
Test this using the httpClient that comes with IDEA
The test results are as follows:
Use MongoRepository
1. Define the interface
/ * * *@authorThe spring-data Repository interface is the Repository interface for spring-data abstraction. You can explore it for yourself
@Repository
public interface UserInfoRepository extends MongoRepository<UserInfo.String> {}Copy the code
Spring Data automatically implements basic CRUD methods through an inherited interface, and also supports methods that can be extended in the form of methods, such as the following keywords:
User-defined query methods. The format is find/get/readBy+ field name + method suffix. The parameters passed to the methods are field values.
Some common method suffixes are as follows:
2. Define the called controller
/ * * *@authorPublic - public - number: a Niu programmer */
@RestController
public class UserInfo2Controller {
@Autowired
private UserInfoRepository userInfoRepository;
@RequestMapping("/getUser2/{userId}")
public Optional<UserInfo> getUserInfo(@PathVariable("userId")String userId){
return userInfoRepository.findById(userId);
}
@PostMapping("/addUser2")
public UserInfo addUserInfo(@RequestBody UserInfo userInfo){
returnuserInfoRepository.save(userInfo); }}Copy the code
3, the results
Test this using the httpClient that comes with IDEA
The test results are as follows:
summary
This article is based on SpringBoot version 2.5.4. Both methods can realize the integration with Spring. You can pay attention to which one you use according to your actual needs, and continue in the next article