spring data使用操作mongodb数据库 springboot

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26584263/article/details/82659182

在IDEA里面使用新建一个maven项目,

项目的结构是如图所示:(注意:springboot 项目中所有的组件必须位于application同级或者子包下才会被扫描到,不然就会报上面的错!)

导入相关的jar包

1、加入jar包依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>


    <dependencies>
        <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.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    </dependencies>

2、在resource文件夹目录下新建application.properites文件

spring.data.mongodb.uri= mongodb://localhost:27017/ceshi

3、新建model下面的类

下面新建的类里面的get,set,toString方法自己加一下呀,这边就不展示了

(1)、Person实体类

public class Person implements Serializable {
    @Id
    private long personId;
    private String name;
    private String address;
    private int age;
    private TypeEnum type;
}

(2)、Teacher实体类

public class Teacher extends  Person {
    private String likeStudent;
    private String teacheCourse;
}

(3)、Student实体类

public class Student extends Person {
    private String likeSport;
    private String likeBook;
    private String school;
}

(4)、TypeEnum枚举类

public enum TypeEnum {
    STUDENT("student", "学生"),TEACHER("teacher", "教师");
    private final String value;
    private final String text;

    public String getValue() {
        return value;
    }

    public String getText() {
        return text;
    }

    TypeEnum(String value, String text) {
        this.value = value;
        this.text = text;
    }
}

4、继承MongoRepository的接口

MongoRepository继承了这个接口可以发现没有更新的方法,所以后面的文章将使用MongoTemplate、MongoOperations来操作是数据库。

repository支持了简单的查询和新增、删除。使用spring data的方法不用实现接口,直接 根据方法名,或者自定义的条件Query来操作。

(1)、StudentRepository

package com.mongodb.demo.repository;

import com.mongodb.demo.model.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface StudentRepository extends MongoRepository<Student, Long> {

    Student findByPersonId(Long personId);

    //分页查询满足条件:name = name and age >= age limit pageable
    @Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}")
    Page<Student> findByNameAndAge2(String name, int age, Pageable pageable);

    int deleteByPersonId(Long personId);

    //删除满足条件:age >= age1 and age <= age2
    @Query("{\"age\":{\"$gte\":?0},\"$lte\":?1}")
    int deleteByAge2(int age1,int age2);

    //分页查询满足条件:name = name and age >= age limit pageable,只会查询相互personId和age的值
    @Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}",fields = "{\"personId\":1,\"age\":1}")
    Page<Student> findByAge2(String name, int age, Pageable pageable);


}

(2)、TeacherRepository

package com.mongodb.demo.repository;

import com.mongodb.demo.model.Teacher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface TeacherRepository extends MongoRepository<Teacher, Long> {
     Teacher findByPersonId(Long personId);

     //分页查询满足条件:name = name and age >= age limit pageable
     @Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}")
     Page<Teacher> findByNameAndAge2(String name, int age, Pageable pageable);

     int deleteByPersonId(Long personId);

     //删除满足条件:age <= age1 and age >= age2
     @Query("{\"age\":{\"$lte\":?0},\"$gte\":?1}")
     int deleteByAge2(int age1,int age2);

     //分页查询满足条件:name = name and age >= age limit pageable,只会查询相互personId和age的值
     @Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}",fields = "{\"personId\":0,\"address\":0}")
     Page<Teacher> findByAge2(String name, int age, Pageable pageable);
}

5、spring boot的启动类

DemoApplication启动类,启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件

package com.mongodb.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@SpringBootApplication
@ServletComponentScan
public class DemoApplication {

    public static void main(String[] args) throws Exception {
     
        SpringApplication.run(DemoApplication.class,args);
    }
}

6、ApplicationStartup监听类

package com.mongodb.demo;

import com.mongodb.demo.model.Student;
import com.mongodb.demo.model.Teacher;
import com.mongodb.demo.model.TypeEnum;
import com.mongodb.demo.repository.StudentRepository;
import com.mongodb.demo.repository.TeacherRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;


/*
* 监听springboot启动类是否启动,启动就执行数据操作
* */
@Configuration
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private TeacherRepository teacherRepository;

    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {  //项目启动后,执行启动消费者方法
        try {
            //新增数据操作
            insert();
            //查找数据操作分页数据
            findByNameAndAge();
            //删除数据
            delete();
            } catch (Exception e) {
            e.printStackTrace();
            }
    }

     //新增数据
    public void insert(){
        Student student = new Student();
        student.setPersonId(20180101L);
        student.setType(TypeEnum.STUDENT);
        student.setAge(22);
        student.setAddress("广东省深圳市福田区");
        student.setName("张三");
        student.setLikeBook("你的孤独虽败犹荣");
        student.setLikeSport("羽毛球");
        student.setSchool("某某大学");

        Teacher teacher = new Teacher();
        teacher.setPersonId(20180101L);
        teacher.setType(TypeEnum.TEACHER);
        teacher.setAge(32);
        teacher.setAddress("广东省深圳市福田区");
        teacher.setName("张三丰");
        teacher.setTeacheCourse("JavaEE");
        teacher.setLikeStudent("张三");
        for(int i = 0 ;i < 15 ; i++){
            student.setAge(student.getAge()-i/2);
            student.setPersonId(student.getPersonId()+i);
            studentRepository.save(student);
            student.setAge(teacher.getAge()+i/2);
            teacher.setPersonId(teacher.getPersonId()+i);
            teacherRepository.save(teacher);
        }

        System.out.println("************************");

        System.out.println("新增学生的数据数量为:"+studentRepository.findAll().size());
        System.out.println("新增老师的数据数量为:"+teacherRepository.findAll().size());
    }

    public void findByNameAndAge(){
        Pageable pageable = PageRequest.of(0,5);
        //获取分页数据,每页5条数,取第0页的数据,
        Page<Student> studentPage = studentRepository.findByNameAndAge2("张三",20,pageable);
        Page<Student> studentPage1 = studentRepository.findByAge2("张三",20,pageable);
        for(Student student : studentPage){
            System.out.println("+++++++++++++:"+student.toString());
        }
        for(Student student : studentPage1){
            System.out.println("-------------:"+student.toString());
        }


        Pageable pageable1 = PageRequest.of(1,3);
        //获取分页数据,每页3条数,取第1页的数据,
        Page<Teacher> teacherPage =teacherRepository.findByNameAndAge2("张三丰",30,pageable1);
        Page<Teacher> teacherPage1 =teacherRepository.findByAge2("张三丰",30,pageable1);

        for(Teacher teacher : teacherPage){
            System.out.println("+++++++++++++:"+teacher.toString());
        }
        for(Teacher teacher : teacherPage1){
            System.out.println("-------------:"+teacher.toString());
        }
    }

    public void delete(){
        try {
            studentRepository.deleteByPersonId(20180101L);
            System.out.println("学生ID为20180101的数据删除成功");
            System.out.println("删除后学生数据数量为:"+studentRepository.findAll().size());

            teacherRepository.deleteByPersonId(20180101L);
            System.out.println("教师ID为20180101的数据删除成功");
            System.out.println("删除后教师数据数量为:"+teacherRepository.findAll().size());

        }catch (Exception e){
            System.err.println("数据删除失败"+e.getMessage());
        }

    }


}

7、测试类

要测试就用测试类,其实测试类就是单独自己去启动启动类来加载执行数据操作

import com.mongodb.demo.DemoApplication;
import com.mongodb.demo.model.Student;
import com.mongodb.demo.model.Teacher;
import com.mongodb.demo.model.TypeEnum;
import com.mongodb.demo.repository.StudentRepository;
import com.mongodb.demo.repository.TeacherRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/*
* 测试类
* */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class StudentRepositoryTest {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private TeacherRepository teacherRepository;


    @Test
    public void test() throws Exception {
        Student student = new Student();
        student.setPersonId(20180101L);
        student.setType(TypeEnum.STUDENT);
        student.setAge(22);
        student.setAddress("广东省深圳市福田区");
        student.setName("张三");
        student.setLikeBook("你的孤独虽败犹荣");
        student.setLikeSport("羽毛球");
        student.setSchool("某某大学");
        studentRepository.save(student);
        System.out.println("************************");
        Teacher teacher = new Teacher();
        teacher.setPersonId(20180102L);
        teacher.setType(TypeEnum.TEACHER);
        teacher.setAge(32);
        teacher.setAddress("广东省深圳市福田区");
        teacher.setName("张三丰");
        teacher.setTeacheCourse("JavaEE");
        teacher.setLikeStudent("张三");
        teacherRepository.save(teacher);
        System.out.println("************************");

        Student student1 = studentRepository.findByPersonId(student.getPersonId());
        Teacher teacher1 = teacherRepository.findByPersonId(teacher.getPersonId());
        System.out.println("新增学生的数据为:"+student1.toString());
        System.out.println("新增老师的数据为:"+teacher1.toString());
    }


}

8、运行结果

 下面的斜体就是运行结果:,由于截图不清晰就用了斜体来展示:

************************
新增学生的数据数量为:15
新增老师的数据数量为:15
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180101, name='张三', address='广东省深圳市福田区', age=22, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180102, name='张三', address='广东省深圳市福田区', age=32, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180104, name='张三', address='广东省深圳市福田区', age=31, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180107, name='张三', address='广东省深圳市福田区', age=32, type=STUDENT}
+++++++++++++:Student{likeSport='羽毛球', likeBook='你的孤独虽败犹荣', school='某某大学'}Person{personId=20180111, name='张三', address='广东省深圳市福田区', age=31, type=STUDENT}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180101, name='null', address='null', age=22, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180102, name='null', address='null', age=32, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180104, name='null', address='null', age=31, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180107, name='null', address='null', age=32, type=null}
-------------:Student{likeSport='null', likeBook='null', school='null'}Person{personId=20180111, name='null', address='null', age=31, type=null}
+++++++++++++:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=20180107, name='张三丰', address='广东省深圳市福田区', age=32, type=TEACHER}
+++++++++++++:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=20180111, name='张三丰', address='广东省深圳市福田区', age=32, type=TEACHER}
+++++++++++++:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=20180116, name='张三丰', address='广东省深圳市福田区', age=32, type=TEACHER}
-------------:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=0, name='张三丰', address='null', age=32, type=TEACHER}
-------------:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=0, name='张三丰', address='null', age=32, type=TEACHER}
-------------:Teacher{likeStudent='张三', teacheCourse='JavaEE'}Person{personId=0, name='张三丰', address='null', age=32, type=TEACHER}
学生ID为20180101的数据删除成功
删除后学生数据数量为:14
教师ID为20180101的数据删除成功
删除后教师数据数量为:14

使用spring data建议使用IDEA来写,方法都是有提示的,可以减少错误。

本案例下载地址:https://download.csdn.net/download/qq_26584263/10661868

《………………………………………………菜鸟起飞中,请各位走过路过的多多指教……………………………………》

猜你喜欢

转载自blog.csdn.net/qq_26584263/article/details/82659182
今日推荐