MongoTemplate and MongoRepository operations are used in springBoot projects

MongoTemplate is more flexible to use, and can be operated in accordance with mongo related operation database language. MongoRepository has good encapsulation, which not only encapsulates the basic add, delete, change and check related construction condition query, but also can customize related methods corresponding to mongo statements in the interface according to rules It's relatively simple to useCopy the code

Maven introduces dependencies

<! [maven spring-boot-starter-data-mongodb] : [maven spring-boot-starter-data-mongodb] : [maven spring-boot-starter-data-mongodb] : [maven spring-boot-starter-data-mongodb] : [maven spring-boot-starter-data-mongodb] : [maven spring-boot-starter-data-mongodb] : [maven spring-boot-starter-data-mongodb]
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Copy the code

Application. properties Configures connection information

# configuration information of parameters The host address The port number To connect the database name spring. Data. The mongo. Uri = mongo: / / 192.168.6.100:27017 / testCopy the code

Springboot startup principle will load 124 configuration classes [automatic configuration class check whether the corresponding class exists or load properties configuration file corresponding properties] automatically generate the corresponding operation object, so as long as add the corresponding dependency and configuration connection properties will automatically create MongoTemplate object So just inject it

Use the MongoTemplate operation set

The model class User corresponding to the document data attributes

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@Document(collection = "user")      // Collection name corresponding to entity model
public class User {
    @Id   // The primary key is automatically generated.
    private String id;
    private String username;
    private Integer age;
    private String password;
    private String address;
}
Copy the code

The controller layer code


import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
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.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/mongo1")
public class TestMongo1 {

    // This object is automatically created in relation to springBoot. This principle is explained at the beginning
    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("create")
    public void createUser(a){
        User user = new User();
        user.setAge(20);
        user.setUsername("test");
        user.setAddress("[email protected]");
        User user1 = mongoTemplate.insert(user);

        // Return with its own generated id
        System.out.println(user1);
    }


    // Query all
    @GetMapping("findAll")
    public void findUser(a) {
        List<User> userList = mongoTemplate.findAll(User.class);
        System.out.println("userList = " + userList);
    }

    // Query by id
    @GetMapping("findById")
    public User getById(a){
        User user = mongoTemplate.findById("614196627e7800008b0037a5", User.class);
        return user;
    }

    // Conditional query
    @GetMapping("findUser")
    public List<User> findUserList(a) {

        // Filter criteria
        Query query = new Query(Criteria
                .where("username").is("Zhang")
                .and("age").is(23));// Execute the query
        List<User> userList = mongoTemplate.find(query, User.class);
        return userList;

    }

    // fuzzy query
    @GetMapping("findLike")
    public List<User> findUsersLikeName(a) {
        // Regular expression fuzzy query []
        String username = "Zhang";
        String regex = String.format("%s%s%s"."^. *", username, ". * $");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        // The name meets the regular expression condition
        Query query = new Query(Criteria.where("username").regex(pattern));
        // Mongodb document corresponding model class
        List<User> userList = mongoTemplate.find(query, User.class);
        return userList;
    }

    // paging query
    @GetMapping("findPage")
    public void findUsersPage(a) {
        String name = "est";
        int pageNo = 1;
        int pageSize = 10;
        
        // Structure condition
        Query query = new Query();
        // Regular expression matches
        String regex = String.format("%s%s%s"."^. *", name, ". * $");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        // Add a condition
        query.addCriteria(Criteria.where("name").regex(pattern));
        // Start counting records
        int totalCount = (int) mongoTemplate.count(query, User.class);
        // Paging query returns the result
        List<User> userList = mongoTemplate.find(query.skip((pageNo - 1) * pageSize).limit(pageSize), User.class);

        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put("list", userList);
        pageMap.put("totalCount",totalCount);
        System.out.println(pageMap);
    }
    / / modify
    @GetMapping("update")
    public void updateUser(a) {
        // Query the entire mongodb document.
        User user = mongoTemplate.findById("5ffbfa2ac290f356edf9b5aa", User.class);
        user.setUsername("test_1");
        user.setAge(25);
        user.setPassword("[email protected]");
        
        // Modify the corresponding data according to the id of the query
        Query query = new Query(Criteria.where("_id").is(user.getId()));
        Update update = new Update();
        update.set("username", user.getUsername());
        update.set("age", user.getAge());
        update.set("password", user.getPassword());
        // Perform the update
        UpdateResult result = mongoTemplate.upsert(query, update, User.class);
        long count = result.getModifiedCount();
        System.out.println(count);
    }

    // Delete operation
    @GetMapping("delete")
    public void delete(a) {
    
       // Construct the condition to delete the corresponding document by id
        Query query =
                new Query(Criteria.where("_id").is("5ffbfa2ac290f356edf9b5aa"));
        DeleteResult result = mongoTemplate.remove(query, User.class);
        longcount = result.getDeletedCount(); System.out.println(count); }}Copy the code

Use the MongoRepository operation collection

Spring Data provides support for mongodb Data access, we just need to inherit MongoRepository class and follow the Spring Data specification

The SpringData method definition specification

1, is not literally statement, and need to meet certain standard 2, query method to find | read | get beginning 3, involving condition query, keyword connection condition attributes with 4, note: The first letter of a conditional attribute must be uppercase. 5. Cascading query of attributes is supported. If the current class has attributes that meet the conditions, the attributes are preferentially used instead of cascading attributes

Implement the UserRepository interface

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserRepository extends MongoRepository<User.String> {

    // These two methods are custom methods based on the matching rules
    List<User> findByUsername(String username);

    List<User> findByUsernameLike(String username);
}
Copy the code

The controller layer code

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/mongo2")
public class TestMongo2 {
    
    @Autowired
    private UserRepository userRepository;
    
    / / add
    @GetMapping("create")
    public User createUser(a){
        User user = new User();
        user.setUsername("Wang Hengrun");
        user.setPassword("admin");
        user.setAge(22);
        user.setAddress("Paidepos225, Haoqiao Town, Nahe District, Xingtai City, Hebei Province");

        User user1 = userRepository.insert(user);
        return user1;
    }

    // Query all
    @GetMapping("findAll")
    public List<User> findAll(a){
        List<User> userList = userRepository.findAll();
        return userList;
    }

    // Query by id
    @GetMapping("findId")
    public User getById(a){
      return userRepository.findById("614196627e7800008b0037a5").get();
    }

    // Conditional query
    @GetMapping("findQuery")
    public List<User> findUserList(a){
        User user = new User();
        user.setUsername("Wang Hengrun");
        user.setAge(22);
        Example<User> userExample = Example.of(user);
        return userRepository.findAll(userExample);
    }

    // fuzzy query
    @GetMapping("findLike")
    public void findUsersLikeName(a) {
        // Create matchers, i.e. how to use query criteria
        ExampleMatcher matcher = ExampleMatcher.matching() // Build the object
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // Change the default string matching method: fuzzy query
                .withIgnoreCase(true); // Change the default case ignore method: ignore case
        User user = new User();
        user.setUsername("Three");
        Example<User> userExample = Example.of(user, matcher);
        List<User> userList = userRepository.findAll(userExample);
        System.out.println(userList);
    }

    // paging query
    @GetMapping("findPage")
    public void findUsersPage(a) {
         Sort sort = Sort.by(Sort.Direction.DESC, "age");
        //0 is the first page
        Pageable pageable = PageRequest.of(0.10, sort);
        // Create matchers, i.e. how to use query criteria
        ExampleMatcher matcher = ExampleMatcher.matching() // Build the object
                        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) // Change the default string matching method: fuzzy query
                .withIgnoreCase(true); // Change the default case ignore method: ignore case
        User user = new User();
        user.setName("Three");
        Example<User> userExample = Example.of(user, matcher);
// Create an instance
        Example<User> example = Example.of(user, matcher);
        Page<User> pages = userRepository.findAll(example, pageable);
        System.out.println(pages);
    }

    / / modify
    @GetMapping("update")
    public void updateUser(a) {
        // Query the document information according to the id
        User user = userRepository.findById("60b8d57ed539ed5b124942de").get();
        user.setUsername("Zhang SAN _1");
        user.setAge(25);
        user.setPassword("[email protected]");
        // Automatically perform updates if the current document exists
        User save = userRepository.save(user);
        System.out.println(save);
    }

    / / delete
    @GetMapping("delete")
    public void delete(a) {
        userRepository.deleteById("60b8d57ed539ed5b124942de");
    }

    // Custom query methods in the interface
    @GetMapping("findByUsername")
    public List<User> findByUsername(String username){
      return userRepository.findByUsername(username);
    }
Copy the code