MongoDB学习(四) — MongoDB 整合Spring Data「终于解决」

MongoDB学习(四) — MongoDB 整合Spring Data「终于解决」1、环境搭建 步骤一:修改pom文件,更新依赖 org.springframework.boot spring…

MongoDB学习(四) --- MongoDB 整合Spring Data

1、环境搭建

  • 步骤一:修改pom文件,更新依赖

    <dependency>
    	<groupId>org.springframework.boot</groupId>
    	<artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
    	<groupId>org.projectlombok</groupId>
    	<artifactId>lombok</artifactId>
    </dependency>
    

    代码100分

  • 步骤二:修改yml文件,配置 mongo连接字符串

    代码100分spring:
      data:
        mongodb:
          uri:  mongodb://root:1234@localhost:27017/admin
    
  • 步骤三:编写 JavaBean,配置文档对应集合

    package com.tqyl.domain;
    
    import lombok.Data;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    import org.springframework.data.mongodb.core.mapping.Field;
    
    /**
     * @author 庭前云落
     * @Date 2020/6/16 8:50
     * @description
     */
    @Data
    @Document(collection = "teacher")
    public class Teacher {
        @Id
        private String teacherId;
        @Field("username")
        private String username;
        private String password;
        private Integer age;
    
        public Teacher() {
        }
    
        public Teacher(String teacherId, String username, String password, Integer age) {
            this.teacherId = teacherId;
            this.username = username;
            this.password = password;
            this.age = age;
        }
    }
    
    
  • 步骤四:编写 dao,继承MongoRepository

    代码100分package com.tqyl.dao;
    
    import com.tqyl.domain.Teacher;
    import org.springframework.data.mongodb.repository.MongoRepository;
    
    import java.util.List;
    
    /**
     * @author 庭前云落
     * @Date 2020/6/16 8:51
     * @description
     */
    public interface TeacherDao extends MongoRepository<Teacher,String> {
    
        public List<Teacher> findByUsername(String username);
    }
    
    
  • 步骤五:编写启动类,使用@ComponentScan扫描 dao

    package com.tqyl;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.ComponentScan;
    
    /**
     * @author 庭前云落
     * @Date 2020/6/16 8:52
     * @description
     */
    @SpringBootApplication
    @ComponentScan(basePackages = "com.tqyl.dao")
    public class TestApplication {
        public static void main(String[] args) {
            SpringApplication.run(TestApplication.class,args);
        }
    }
    
    
  • 步骤六:编写测试类,获得 dao 实现类

    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = TestApplication.class)
    public class TestRepository {
        @Resource
        private TeacherDao teacherDao;
    }
    

2、基础操作

2.1、查询所有

   @Test
    public void testFindAll(){
        //查询
        List<Teacher> list = teacherDao.findAll();
        System.out.println(list);
    }

2.2、排序查询

   @Test
    public void testDemo01(){
        //排序
        //List<Teacher> list = teacherRepository.findAll(Sort.by("password"));
        List<Teacher> list = teacherDao.findAll(Sort.by(Sort.Order.desc("password")));

        for (Teacher teacher : list) {
            System.out.println(teacher);
        }
    }

2.3、分页

  • 分页基本操作
    @Test
    public void testDemo02(){
        //分页
        int page = 0;   //从0开始
        int size = 2;
        Page<Teacher> teacherPage = teacherDao.findAll(PageRequest.of(page, size));

        //处理分页数据
        //1 获得分页内容
        List<Teacher> list = teacherPage.getContent();
        //2 获得总记录数
        long total = teacherPage.getTotalElements();

        System.out.println("总条数:" + total);
        for (Teacher teacher : list) {
            System.out.println(teacher);
        }
    }
  • 分页 jdk8 ForEach
    @Test
    public void testDemo03() {
        //分页
        int page = 0;   //从0开始
        int size = 2;
        Page<Teacher> teacherPage = teacherDao.findAll(PageRequest.of(page, size));

        //遍历数据
        // JDK8提供forEach,使用箭头函数进行遍历
        teacherPage.forEach(teacher -> System.out.println(teacher) );

        // 打印简化版
        teacherPage.forEach(System.out::println);
    }

2.5、添加

    @Test
    public void testDemo04(){
        //准备数据
        Teacher teacher = new Teacher();
        teacher.setUsername("王五");
        teacher.setPassword("666777");
        teacher.setAge(30);

        //插入数据
        teacherDao.insert( teacher );
    }

2.6、通过ID查询

    @Test
    public void testDemo05(){
        //通过id查询
        Optional<Teacher> optional = teacherDao.findById("5ee83ccf9d1c6904d8768ca8");
        //Optional 用于统一规范空指针异常处理
        if(optional.isPresent()){  // teacher != null
            Teacher teacher = optional.get();
            System.out.println(teacher);
        } else {
            System.out.println("没有数据");
        }
    }

2.7、更新

  • 更新采用save方法
    • 如果数据存在,将发生更新操作
    • 如果数据不存在,将发生添加操作
    @Test
    public void testDemo06(){
        //更新操作
        //1 查询
        Optional<Teacher> optional = teacherDao.findById("5ee83ccf9d1c6904d8768ca8");

        if(optional.isPresent()) {
            //2 修改数据
            Teacher teacher = optional.get();
            teacher.setUsername("王武");
            //3 更新
            teacherDao.save(teacher);
        }
    }

2.8、删除

  • deleteById() :通过id删除
  • deleteAll() :删除所有
    @Test
    public void testDemo07(){
        //删除
        teacherDao.deleteById("5ee83ccf9d1c6904d8768ca8");
    }

2.9、自定义dao

  • 在dao中,可以通过约定进行条件查询
    • 前缀:findBy
    • 查询条件:字段名
    • 关键字:And、Or、Like 等
  • TeacherRepository
 public List<Teacher> findByUsername(String username);
    @Test
    public void testDemo08(){
        //自定义查询
        List<Teacher> list = teacherRepository.findByUsername("tom");
        System.out.println(list);

    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/7872.html

(0)
上一篇 2023-03-12 12:30
下一篇 2023-03-12

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注