首页 >> 大全

spring data使用操作mongodb数据库 springboot

2023-08-04 大全 29 作者:考证青年

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

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

_dao操作数据库

导入相关的jar包

1、加入jar包依赖

    org.springframework.bootspring-boot-starter-parent2.0.1.RELEASEorg.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-testtestorg.springframework.bootspring-boot-devtoolstrueorg.springframework.bootspring-boot-starter-data-mongodb

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

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

3、新建model下面的类

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

(1)、实体类

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

(2)、实体类

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

(3)、实体类

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

(4)、枚举类

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

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

235909a507b2ddf15760d67a839d8b17

(1)、

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 findByPersonId(Long personId);//分页查询满足条件:name = name and age >= age limit pageable@Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}")Page 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 findByAge2(String name, int age, Pageable pageable);}

(2)、

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 findByPersonId(Long personId);//分页查询满足条件:name = name and age >= age limit pageable@Query(value = "{\"name\":{\"$regex\":?0},\"age\":{\"$gte\":?1}}")Page 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 findByAge2(String name, int age, Pageable pageable);
}

5、 boot的启动类

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

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、监听类

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 {@Autowiredprivate StudentRepository studentRepository;@Autowiredprivate 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 studentPage = studentRepository.findByNameAndAge2("张三",20,pageable);Page 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 teacherPage =teacherRepository.findByNameAndAge2("张三丰",30,pageable1);Page 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());@Autowiredprivate StudentRepository studentRepository;@Autowiredprivate TeacherRepository teacherRepository;@Testpublic 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

+++++++++++++:{='羽毛球', ='你的孤独虽败犹荣', ='某某大学'}{=, name='张三', ='广东省深圳市福田区', age=22, type=}

+++++++++++++:{='羽毛球', ='你的孤独虽败犹荣', ='某某大学'}{=, name='张三', ='广东省深圳市福田区', age=32, type=}

+++++++++++++:{='羽毛球', ='你的孤独虽败犹荣', ='某某大学'}{=, name='张三', ='广东省深圳市福田区', age=31, type=}

_dao操作数据库

+++++++++++++:{='羽毛球', ='你的孤独虽败犹荣', ='某某大学'}{=, name='张三', ='广东省深圳市福田区', age=32, type=}

+++++++++++++:{='羽毛球', ='你的孤独虽败犹荣', ='某某大学'}{=, name='张三', ='广东省深圳市福田区', age=31, type=}

-------------:{='null', ='null', ='null'}{=, name='null', ='null', age=22, type=null}

-------------:{='null', ='null', ='null'}{=, name='null', ='null', age=32, type=null}

-------------:{='null', ='null', ='null'}{=, name='null', ='null', age=31, type=null}

-------------:{='null', ='null', ='null'}{=, name='null', ='null', age=32, type=null}

-------------:{='null', ='null', ='null'}{=, name='null', ='null', age=31, type=null}

+++++++++++++:{='张三', =''}{=, name='张三丰', ='广东省深圳市福田区', age=32, type=}

+++++++++++++:{='张三', =''}{=, name='张三丰', ='广东省深圳市福田区', age=32, type=}

+++++++++++++:{='张三', =''}{=, name='张三丰', ='广东省深圳市福田区', age=32, type=}

-------------:{='张三', =''}{=0, name='张三丰', ='null', age=32, type=}

-------------:{='张三', =''}{=0, name='张三丰', ='null', age=32, type=}

-------------:{='张三', =''}{=0, name='张三丰', ='null', age=32, type=}

学生ID为的数据删除成功

删除后学生数据数量为:14

教师ID为的数据删除成功

删除后教师数据数量为:14

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

本案例下载地址:

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

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了