MongoDB(五)——MongoRepository操作MongoDB

MongoRepository操作MongoDB

环境搭建

添加Repository类

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

}

添加操作

package com.study;

import com.study.mongodb.entiity.User;
import com.study.mongodb.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class SpringbootMongoDbApplicationTest1 {
    @Autowired
    private UserRepository userRepository;

    //添加操作
    @Test
    void create(){
        User user = new User();
        user.setAge(20);
        user.setName("zhangsan");
        user.setEmail("963330213@qq.com");
        User user1 = userRepository.save(user);
        System.out.println(user1);
    }
}

image

查询操作

1.查询所有

 //查询所有
    @Test
    void findAll(){
        List<User> userList = userRepository.findAll();
        System.out.println(userList);
    }

image
2.根据id查询

    //根据id查询
    @Test
    void findById(){
        User user = userRepository.findById("611a2f1f5e7124132f365fa7").get();
        System.out.println(user);
    }

image

3.条件查询

    //条件查询
    @Test
    void findUserList(){
        //name = zhangsan and age = 20
        User user = new User();
        user.setName("zhangsan");
        user.setAge(20);
        Example<User> userExample = Example.of(user);
        List<User> users = userRepository.findAll(userExample);
        System.out.println(users);
    }

image

4.模糊查询

    //模糊查询
    @Test
    void findLikeUserList(){
        //设置模糊查询匹配规则
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);//忽略大小写
        User user = new User();
        user.setName("z"); //包含z的数据
        Example<User> userExample = Example.of(user,matcher);
        List<User> users = userRepository.findAll(userExample);
        System.out.println(users);
    }

image

5.分页查询

    //分页查询
    @Test
    void findPageUserList(){
        //分页
        Pageable pageable = PageRequest.of(0, 3);//0代表第一页,3显示3个字段
        User user = new User();
        user.setName("zhangsan");
        Example<User> userExample = Example.of(user);
        Page<User> page = userRepository.findAll(userExample, pageable);
        System.out.println(page);
    }

修改操作

    //修改操作
    @Test
    void updateUser(){
        User user = userRepository.findById("611a2f1f5e7124132f365fa7").get();
        user.setAge(18);
        user.setName("lisi");
        User save = userRepository.save(user); //有id则修改,无id则变成添加操作
        System.out.println(save);
    }

image

删除操作

 //删除操作
    @Test
    void deleteUser(){
        userRepository.deleteById("611a2f1f5e7124132f365fa7");
    }
posted @ 2021-08-16 17:49  转身刹那的潇洒  阅读(4053)  评论(0编辑  收藏  举报