Spring boot integrates mongodb

Spring boot integrates mongodb

1. Introduction to Spring boot integration mongodb

spring-data-mongodb provides two ways to access mongodb, MongoTemplate and MongoRepository .

  • MongoRepository is simple to operate
  • MongoTemplate is flexible in operation

We can flexibly apply these two ways to operate mongodb in the project. The disadvantage of MongoRepository is that it is not flexible enough, and MongoTemplate can just make up for the shortcomings.

2. Build the project environment

2.1, create a springboot project

Insert picture description here

2.2. Introduce dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </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>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.10.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

2.3, add configuration

Add MongoDB configuration in application.properties file

spring.data.mongodb.uri=mongodb://127.0.0.1:27017/test

3. Develop CRUD based on MongoTemplate

3.1, MongoTemplate common methods

mongoTemplate.findAll(User.class): Query all the data of the User document
mongoTemplate.findById(, User.class): Query the data of the User document id as id
mongoTemplate.find(query, User.class);: According to the query in the query Conditional query
mongoTemplate.upsert(query, update, User.class): modify
mongoTemplate.remove(query, User.class): delete
mongoTemplate.insert(User): add
Query object
1. Create a query object (used to encapsulate all Condition object), and then create a criteria object (used to construct conditions)
2. Precise conditions: criteria.and("key").is("conditions")
Fuzzy conditions: criteria.and("key").regex(" Conditions")
3. Encapsulation conditions: query.addCriteria(criteria)
4. Greater than (create new criteria): Criteria gt = Criteria.where("key").gt ("criteria") is
less than (create new criteria): Criteria lt = Criteria.where("key").lt("condition")
5. Query.addCriteria(new Criteria().andOperator(gt,lt));
6. There can only be one andOperator() in a query. The parameter can also be an array of Criteria.
7. Sort: query.with(new Sort(Sort.Direction.ASC, “age”). and(new Sort(Sort.Direction.DESC, “date”)))

3.2, create an entity class

@Data
@Document("User")
public class User {

    @Id
    private String id;
    private String name;
    private Integer age;
    private String email;
    private String createDate;
}

3.3. Write test classes to test additions, deletions, and changes based on MongoTemplate development

3.3.1, new data

Insert picture description here
@Autowired
    private MongoTemplate mongoTemplate;

    //添加操作
    @Test
    void contextLoads() {
        User user = new User();
        user.setAge(20);
        user.setName("test");
        user.setEmail("[email protected]");
        User user1 = mongoTemplate.insert(user);
        System.out.println(user1);
    }

Console output

Insert picture description here

3.3.2, query collection (table) all

Insert picture description here
//查询所有记录
@Test
 public void findAll(){
     List<User> all = mongoTemplate.findAll(User.class);
     System.out.println(all);
 }
Insert picture description here

3.3.3, query by id

Insert picture description here
 //根据id查询
 @Test
 public void findId(){
     User user = mongoTemplate.findById("60b4b3ca861699233d33f3e2", User.class);
     System.out.println(user);
 }
Insert picture description here

3.3.4, conditional query

Insert picture description here
//条件查询
@Test
 public void findUserList(){
     Query query = new Query(Criteria.where("name").is("test").and("age").is(20));
     List<User> users = mongoTemplate.find(query, User.class);
     System.out.println(users);
 }
Insert picture description here

3.3.5, fuzzy query

Pattern.compile function usage

 //模糊条件查询
    @Test
    public void findLikeUserList(){
//        name like test
        String name = "est";
        String regex = String.format("%s%s%s", "^.*", name, ".*$");
        /*1、在使用Pattern.compile函数时,可以加入控制正则表达式的匹配行为的参数:
        Pattern Pattern.compile(String regex, int flag)
        2、regex设置匹配规则
        3、Pattern.CASE_INSENSITIVE,这个标志能让表达式忽略大小写进行匹配。*/
        Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
        //创建一个query对象(用来封装所有条件对象),再创建一个criteria对象(用来构建条件)
        Query query = new Query(//构建查询条件
                Criteria.where("name").regex(pattern));
        List<User> users = mongoTemplate.find(query, User.class);
        System.out.println(users);
    }

Query result: the user with est in the name is queried

Insert picture description here

3.3.6, paging query with conditions

//分页查询(带条件)
@Test
 public void pageLikeUserList(){
     int pageNo = 1;//设置当前页
     int pageSize = 3;//设置每页显示的记录数

     //条件构建
     String name = "est";
     String regex = String.format("%s%s%s", "^.*", name, ".*$");
     /*1、在使用Pattern.compile函数时,可以加入控制正则表达式的匹配行为的参数:
     Pattern Pattern.compile(String regex, int flag)
     2、regex设置匹配规则
     3、Pattern.CASE_INSENSITIVE,这个标志能让表达式忽略大小写进行匹配。*/
     Pattern pattern = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
     //创建一个query对象(用来封装所有条件对象),再创建一个criteria对象(用来构建条件)
     Query query = new Query(//构建查询条件
             Criteria.where("name").regex(pattern));

     //分页构建
     //查询数来集合(表)中的总记录数
     long count = mongoTemplate.count(query, User.class);
     List<User> users = mongoTemplate.find(
             query.skip((pageNo - 1) * pageSize).limit(pageSize), User.class);
     System.out.println(count);
     System.out.println(users);
 }
Insert picture description here

3.3.7, modify operation

Insert picture description here
 //修改操作
@Test
public void  updateUser(){
    //根据id查询
    User user = mongoTemplate.findById("60b4f89db925b61fbf529591", User.class);
    //修改值
    user.setName("test_02");
    user.setAge(2);
    user.setEmail("[email protected]");

    //调用方法实现修改
    Query query = new Query(Criteria.where("_id").is(user.getId()));
    Update update = new Update();
    update.set("name",user.getName());
    update.set("age",user.getAge());
    update.set("email",user.getEmail());
    //调用mongoTemplate的修改方法实现修改
    UpdateResult upsert = mongoTemplate.upsert(query, update, User.class);
    long modifiedCount = upsert.getModifiedCount();//获取到修改受影响的行数
    System.out.println("受影响的条数:"+modifiedCount);
}
Insert picture description here

3.3.8, delete operation

Insert picture description here
//删除条件
@Test
 public void deleteUser(){
     Query query = new Query(Criteria.where("_id").is("60b4b3ca861699233d33f3e2"));
     DeleteResult remove = mongoTemplate.remove(query, User.class);
     long deletedCount = remove.getDeletedCount();
     System.out.println("删除的条数:"+deletedCount);
 }//删除条件
 @Test
 public void deleteUser(){
     Query query = new Query(Criteria.where("_id").is("60b4b3ca861699233d33f3e2"));
     DeleteResult remove = mongoTemplate.remove(query, User.class);
     long deletedCount = remove.getDeletedCount();
     System.out.println("删除的条数:"+deletedCount);
 }

Console output:

Insert picture description here


check mongoDB, the data has been deleted

Insert picture description here

4. Develop CRUD based on MongoRepository

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

4.1, SpringData method definition specification

Insert picture description here
Insert picture description here

1. It is not declared casually, but needs to conform to certain specifications.
2. The query method starts with find | read | get
3. When a conditional query is involved, the attribute of the condition is connected with the condition keyword
4. It should be noted that the first letter of the condition attribute Requires uppercase
5. Supports cascading query of attributes, but if the current class has qualified attributes, it will be used first instead of cascading attributes. If cascading attributes are needed, use _ to force connection between attributes

4.2, add Repository interface

Insert picture description here
import com.demomongodb.entity.User;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
/**
 * @Description :
 * @Author :lenovo
 * @Date :2021/6/1 10:54
 */
@Repository
public interface UserRepository extends MongoRepository<User,String> {
}

4.3 Add test class, test CRUD

4.3.1, add operation

Insert picture description here
@Autowired
private UserRepository userRepository;

 //添加操作
 @Test
 public void save(){
     User user = new User();
     user.setName("ertong");
     user.setAge(20);
     user.setEmail("[email protected]");
     User user1 = userRepository.save(user);
     System.out.println(user1);
 }
Insert picture description here

4.3.2, query all

//查询所有
@Test
public void findAll(){
    List<User> lists = userRepository.findAll();
    for(User user:lists){
        System.out.println(user);
    }
}
Insert picture description here

4.3.2, query by id

//根据id查询
@Test
public void findById(){
    User user = userRepository.findById("60b4b491861699233d33f3e3").get();
    System.out.println(user);
}
Insert picture description here

4.3.3, condition query

Use Example example = Example.of(user); to encapsulate query conditions

//条件查询
 @Test
 public void findUserList(){
     User user = new User();
     user.setName("ertong");
     user.setAge(20);
     Example<User> example = Example.of(user);
     List<User> all = userRepository.findAll(example);
     System.out.println(all);
 }
Insert picture description here

4.3.4, fuzzy condition query

Insert picture description here
//模糊条件查询
@Test
public void findLikeUserList(){
    ///创建匹配器,即如何使用查询条件
    ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)//改变默认字符串匹配方式:模糊查询
            .withIgnoreCase(true);//改变默认大小写忽略方式:忽略大小写

    User user = new User();
    user.setName("e");
    user.setAge(20);
    Example<User> example = Example.of(user,matcher);
    List<User> all = userRepository.findAll(example);
    System.out.println(all);
}
Insert picture description here

4.3.5, pagination query

//分页查询
@Test
public void findPageUserAll(){
    //设置分页参数
    //0代表第一页
    Pageable pageable = PageRequest.of(0, 3);
    //查询条件
    User user = new User();
    user.setName("test");
    Example<User> userExample = Example.of(user);//查询条件
    Page<User> page = userRepository.findAll(userExample, pageable);
    System.out.println(page.getContent());
}
Insert picture description here

4.3.6, modification

Insert picture description here
//修改操作
@Test
public void updateUser(){
    //先根据id出要修改的用户
    User user = userRepository.findById("60b5a37209aa4d6face6bacd").get();
    //设置修改的值
    user.setName("haha");
    user.setAge(23);
    user.setEmail("[email protected]");
    User user1 = userRepository.save(user);
    System.out.println(user1);
}
Insert picture description here

4.3.6, delete

Before executing the delete, first query some data in the user table of the database to

Insert picture description here


execute the delete operation

//删除
@Test
public void delete(){
   userRepository.deleteById("60b5a37209aa4d6face6bacd");
}

Query the user table of the test database again, the data has been deleted

Insert picture description here