SpringBoot——整合MongoDB详解
短信预约 -IT技能 免费直播动态提醒
引入依赖
<dependency> <groupId>org.springframework.bootgroupId> <artifactId>spring-boot-starter-data-mongodbartifactId>dependency>
配置文件
spring: data: mongodb: host: 127.0.0.1 database: test port: 27017 # 也可以使用uri mongodb://127.0.0.1:27017/test
创建实体类
public class Student implements Serializable{ @Id private String studentId; private String studentName; private Integer studentAge; private Double studentScore; private Date studentBirthday; public Student(String studentId, String studentName, Integer studentAge, Double studentScore, Date studentBirthday) { this.studentId = studentId; this.studentName = studentName; this.studentAge = studentAge; this.studentScore = studentScore; this.studentBirthday = studentBirthday; } public Student() { } public String getStudentId() { return studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Integer getStudentAge() { return studentAge; } public void setStudentAge(Integer studentAge) { this.studentAge = studentAge; } public Double getStudentScore() { return studentScore; } public void setStudentScore(Double studentScore) { this.studentScore = studentScore; } public Date getStudentBirthday() { return studentBirthday; } public void setStudentBirthday(Date studentBirthday) { this.studentBirthday = studentBirthday; } @Override public String toString() { return "Student{" + "studentId='" + studentId + '\'' + ", studentName='" + studentName + '\'' + ", studentAge=" + studentAge + ", studentScore=" + studentScore + ", studentBirthday=" + studentBirthday + '}'; }}
dao层
1、JPA方式
public interface StudentRepository extends MongoRepository<Student, String> {}
测试:
import data.dao.StudentRepository;import data.domain.Student;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.domain.*;import java.util.*;@SpringBootTestpublic class StudentRepositoryTest { @Autowired private StudentRepository studentRepository; @Test public void insertOne() { Student student = new Student("009", "tom", 18, 88.2d, new Date()); studentRepository.insert(student); } @Test public void insertMany() { Student student1 = new Student("002", "jerry", 19, 38.2d, new Date()); Student student2 = new Student("003", "mike", 20, 78.2d, new Date()); List<Student> list = new ArrayList<>(); list.add(student1); list.add(student2); studentRepository.insert(list); } @Test public void update() { Optional<Student> op = studentRepository.findById("001"); Student student = op.get(); student.setStudentAge(222); studentRepository.save(student); } @Test public void query() { //根据Id查询单个对象 Optional<Student> stuOp = studentRepository.findById("001"); System.out.println(stuOp.get()); //根据字段查询单个对象 Student student = new Student(); student.setStudentAge(19); Optional<Student> stuOp1 = studentRepository.findOne(Example.of(student)); System.out.println(stuOp1.get()); //根据id列表查询多个对象 Iterable<Student> itStu = studentRepository.findAllById(Arrays.asList(new String[]{"001", "002"})); Iterator<Student> itor = itStu.iterator(); while (itor.hasNext()) System.out.println(itor.next()); //查询所有 List<Student> all = studentRepository.findAll(); //查询所有并排序 List<Student> all1 = studentRepository.findAll(Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName"))); for (Student stu : all1) System.out.println(stu); //根据条件查询所有并排序 Student student1 = new Student(); student1.setStudentName("tom"); List<Student> all2 = studentRepository.findAll(Example.of(student1), Sort.by(Sort.Order.desc("studentId"), Sort.Order.asc("studentName"))); for (Student stu : all2) System.out.println(stu); //根据条件查询所有并排序,且分页 Pageable pageable = PageRequest.of(0, 2); Page<Student> all3 = studentRepository.findAll(pageable); List<Student> content = all3.getContent(); for (Student stu : content) System.out.println(stu); } @Test public void other() { //count long count = studentRepository.count(); System.out.println(count); Student student = new Student(); student.setStudentAge(18); long count1 = studentRepository.count(Example.of(student)); System.out.println(count1); //exists boolean exists = studentRepository.exists(Example.of(student)); System.out.println(exists); boolean b = studentRepository.existsById("001"); System.out.println(b); } @Test public void remove() { //根据id删除单个对象 studentRepository.deleteById("001"); //根据字段删除 Student student = new Student(); student.setStudentAge(20); studentRepository.delete(student); //删除所有 studentRepository.deleteAll(); //根据字段删除多个 Student student1 = new Student(); student1.setStudentName("jerry"); List<Student> list = new ArrayList<>(); list.add(student); list.add(student1); studentRepository.deleteAll(list); }}
2、MongoTemplate方式
dao接口:
public interface StudentDao { //插入单个对象 void addOne(Student student); //根据id删除单个对象 void deleteOneById(String studentId); //修改单个对象 void updateOne(Student student); //根据id获取单个对象 Student findOneById(String studentId); //获取全部学生 List<Student> findAll();}
实现类:
public class StudentDaoImpl implements StudentDao { @Autowired private MongoTemplate mongoTemplate; @Override public void addOne(Student student) { mongoTemplate.save(student); } @Override public void deleteOneById(String studentId) { Student stu = mongoTemplate.findById(studentId, Student.class); if (stu != null) mongoTemplate.remove(stu); } @Override public void updateOne(Student student) { mongoTemplate.save(student); } @Override public Student findOneById(String studentId) { return mongoTemplate.findById(studentId, Student.class); } @Override public List<Student> findAll() { return mongoTemplate.findAll(Student.class); }}
测试类:
@SpringBootTestpublic class StudentDaoTest { @Autowired private StudentDao studentDao; @Test void addOneStudent(){// 插入10行 for (Integer count = 0; count < 10; count++) { Student student = new Student(); student.setStudentId("study_"+count); student.setStudentName("Echo"+count); student.setStudentAge(count); student.setStudentScore(98.5-count); student.setStudentBirthday(new Date()); studentDao.addOne(student); } } @Test void deleteOneStudentByStudentId(){// 删除id为study_0的学生 studentDao.deleteOneById("study_0"); } @Test void updateOneStudent(){// 修改id为study_1的Student年龄为21 Student student = studentDao.findOneById("study_1"); student.setStudentAge(21); studentDao.updateOne(student); } @Test void getOneStudentByStudentId(){ System.out.println(studentDao.findOneById("study_1")); } @Test void getAllStudent(){ List<Student> studentList = studentDao.findAll(); studentList.forEach(System.out::println); }}
MongoTemplate
1、查询
is查询:
Query query = new Query();// where...is... 相当于 where ? = ?query.addCriteria(Criteria.where("数据库字段名").is("你的参数"));// findOne 返回的是一个对象 Class代表你的表对应的映射类mongoTemplate.findOne(query, Class.class);// find 返回的是数组mongoTemplate.find(query, Class.class);
in查询:
ArrayList<String> list = new ArrayList<>();// list代表你的数据Query query = Query.query(Criteria.where("数据库字段").in(list));mongoTemplate.find(query, Class.class);// 如果想要查询指定的数据是否在数据库的数组中,可以用以下方法Query query = Query.query(Criteria.where("数据库字段(数组)").is("你的数组"));
字符模糊查询:
Query query = Query.query(Criteria.where("name").regex("小"));
指定字段不返回:
query.fields().exclude("field");
数组中添加或删除一条数据:
Query query = Query.query(Criteria.where("_id").is("id"));Update update = new Update();// push方法可以在数组中添加一条数据// pull方法可以在数组中删除一条数据// update.pull()update.push("字段名称", "data");mongoTemplate.updateFirst(query, update, Class.class);
批量添加:
ArrayList<Class> list = new ArrayList<>();mongoTemplate.insert(list, Class.class);
数组查询:
数组格式:{ name:"小明", age:13, friends:[ { name:"小王", age:12 }, { name:"小李", age:18 } ]}当要查询朋友中姓名为小王时Query query = new Query();query.addCriteria(Criteria.where("friends.$.name").is("小王"));mongoTemplate.find(query, User.class);同样更新时也是一样,但是注意,更新时查询条件需要添加query.addCriteria(Criteria.where("friends").elemMatch(Criteria.where("name").is("小王"));Update update = Update.update("friends.$.friends", "小赵");
数字字符串排序操作
对数据库中数字字符串排序:加上这一行就行了 亲身体验query.collation(Collation.of("zh").numericOrdering(true));还有根据字符串排序时又是顺序并不是我们所想的字典序,加上下面这个也okquery.collation(Collation.of("zh"));
分页:
//分页query.limit(10);//排序Sort sort=Sort.by(Sort.Direction.DESC,"timestamp");query.with(sort);
criteria:
关键字 | 解释 |
---|---|
eq | 等于,第一个参数是对象属性,第二个参数是值 |
allEq | 参数为一个Map对象,相当于多个eq的叠加 |
gt | 大于 |
ge | 大于等于 |
lt | 小于 |
le | 小于等于 |
between | 在两个值之间Expression.between(“age”,new Integer(10),new Integer(20)); |
like | like查询 |
in | in查询 |
2、更新
User user = new User();user.setId("5d1312aeb1829c279c6c256b");user.setName("admin");user.setAddress("测试");Query query = Query.query(Criteria.where("_id").is("5d1312aeb1829c279c6c256b"));Update update = Update.update("name","zs");// 更新一条数据mongoTemplate.updateFirst(query,update, User.class);mongoTemplate.updateFirst(query,update, "mongodb_user");mongoTemplate.updateFirst(query,update, User.class,"mongodb_user");// 更新多条数据mongoTemplate.updateMulti(query,update, User.class);mongoTemplate.updateMulti(query,update,"mongodb_user");mongoTemplate.updateMulti(query,update, User.class,"mongodb_user");// 更新数据,如果数据不存在就新增mongoTemplate.upsert(query,update, User.class);mongoTemplate.upsert(query,update,"mongodb_user");mongoTemplate.upsert(query,update, User.class,"mongodb_user");
3、插入
List<User> list = new ArrayList<>();User user= new User();//user.setName("admin");user.setAddress("测试");list.add(user);// 保存对象到mongodbmongoTemplate.save(user);mongoTemplate.insert(user);// 根据集合名称保存对象到mongodbmongoTemplate.save(user,"mongodb_user");mongoTemplate.insert(user,"mongodb_user");// 根据集合名称保存list到mongodbmongoTemplate.save(list,"mongodb_user");mongoTemplate.insert(list,"mongodb_user");mongoTemplate.insert(list,User.class);
4、删除
List<MongoDbJavaTest> list = new ArrayList<>();User user= new User();user.setId("5d1312aeb1829c279c6c256b");list.add(user);Query query = Query.query(Criteria.where("_id").in("5d1312aeb1829c279c6c256b","5d13133ab1829c29d02ce29c"));// 根据条件删除mongoTemplate.remove(query);mongoTemplate.remove(user);mongoTemplate.remove(User.class);// 根据条件删除(可删除多条)mongoTemplate.remove(query,User.class,"mongodb_user");
来源地址:https://blog.csdn.net/cold___play/article/details/130570308
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341