Logo

Spring boot集成mongodb使用MongoRepository完成CURD和复杂查询

photo

2020年12月26日

Spring Data简介

Spring Data 是spring的组件之一,主要目的是为了让开发者再工作中能更加轻松的完成CURD,简化代码应该是所有框架的目的吧。今天介绍的Spring-data-mongodb只是其中的一个模块而已,Spring团队的强大不言而喻,有兴趣的请移步官网查看更多模块。
Spring-Data

Spring Data Jpa 方法定义规范

网上的博文关于这部分大同小异,这里只贴部分内容,详细规则可以参考官方文档。这些方法只是在特定情况下才用的到,比如MongoRepository不能完成的工作,但是在本人实际工作中MongoRepository已经覆盖了9成以上的需求,如果你感觉有什么需求它完成不了,很有可能是没有找对方法。
Spring-Data-Jpa

在这里插入图片描述在这里插入图片描述

MongoRepository实战操作

  1. 新建测试项目,spring boot新建项目可以选择访问官网,并添加Web和Mongodb依赖即可。如下图所示
    在这里插入图片描述
  2. 打开项目,并修改application.properties文件添加数据源,如下所示:
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=testmongodb
  1. 分别新建实体类User/Repository接口UserRespository/控制器UserController
public class User {
   private String id;
   private String userName;
   private String password;
   private int age;
   private long createTime;
   public String getId() {
      return id;
   }
   public void setId(String id) {
      this.id = id;
   }
   public String getUserName() {
      return userName;
   }
   public void setUserName(String userName) {
      this.userName = userName;
   }
   public String getPassword() {
      return password;
   }
   public void setPassword(String password) {
      this.password = password;
   }
   public int getAge() {
      return age;
   }
   public void setAge(int age) {
      this.age = age;
   }
   public long getCreateTime() {
      return createTime;
   }
   public void setCreateTime(long createTime) {
      this.createTime = createTime;
   }  
}
package com.ppw.mongoexample.repository;

import org.springframework.data.mongodb.repository.MongoRepository;

import com.ppw.mongoexample.model.User;

public interface UserRepository extends MongoRepository<User, String>{
	public Page<User> findByUserNameLike(String userName, Pageable pageable);
}
package com.ppw.mongoexample.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpStatus;
import com.ppw.mongoexample.model.User;
import com.ppw.mongoexample.repository.UserRepository;

@RestController
@RequestMapping("/v1/user")
public class UserController {

   @Autowired
   private UserRepository userRepository;
   
   @ResponseStatus(HttpStatus.CREATED)
   @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
   public User createUser(@RequestBody User user) {
      return userRepository.save(user);
   }
   
   /**
    * 根据id查询
    * @param id
    * @return
    */
   @GetMapping(value="/{id}")
   public User readUserById(@PathVariable("id") String id){
      return userRepository.findOne(id);
   }
   
   /**
    * 根据一个或者多个属性查询单个结果
    * @param name
    * @return
    */
   @GetMapping(value="/name/{name}")
   public User readUserByName(@PathVariable("name") String name){
      User user = new User();
      user.setUserName(name);
      ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("age","createTime");
      Example<User> example = Example.of(user, matcher);
      return userRepository.findOne(example);
   }
   
   /**
    * 根据一个或者多个属性分页查询 
    * @param pageNumber
    * @param pageSize
    * @return
    */
   @GetMapping(value = "/page/{pageNumber}/pagesize/{pageSize}/name/{name}")
   public Page<User> readUsersByPage(@PathVariable("pageNumber") int pageNumber,
         @PathVariable("pageSize") int pageSize,@PathVariable("name") String name) {
      User user = new User();
      user.setUserName(name);
      ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("age","createTime");
      Example<User> example = Example.of(user, matcher);
      if (pageNumber < 1) {
         pageNumber = 1;
      } else if (pageSize == 0) {
         pageSize = 20;
      }
      
      PageRequest pageable = new PageRequest(pageNumber - 1, pageSize);
      return userRepository.findAll(example, pageable);
   }
   
   /**
    * 根据用户年龄升序排序
    * @return
    */
   @GetMapping
   public List<User> readUsers(){
      
      Order order = new Order(Direction.ASC,"age");
      Sort sort = new Sort(order);
      return userRepository.findAll(sort);
   }
   
   /**
    * 模糊查询带分页
    * @param pageNumber
    * @param pageSize
    * @param keyWords
    * @return
    */
   @GetMapping(value = "/page/{pageNumber}/pagesize/{pageSize}/keyword/{keyWords}")
   public Page<User> readUsersByKeywords(@PathVariable("pageNumber") int pageNumber,
         @PathVariable("pageSize") int pageSize,@PathVariable("keyWords") String keyWords) {
      if (keyWords == null) {
         keyWords = "";
      }
      if (pageNumber < 1) {
         pageNumber = 1;
      } else if (pageSize == 0) {
         pageSize = 20;
      }
      PageRequest pageable = new PageRequest(pageNumber - 1, pageSize);
      return userRepository.findByUserNameLike(keyWords, pageable);
   }
   
   @ResponseStatus(HttpStatus.OK)
   @DeleteMapping(value="/{id}")
   public void removeUser(@PathVariable("id") String id) {
      userRepository.delete(id);
   }
}

Postman测试部分接口结果如下图所示

1.新建用户
在这里插入图片描述2.根据用户名模糊查询并分页
在这里插入图片描述3.根据年龄升序排序
在这里插入图片描述

Mongodb截图如下

在这里插入图片描述

注意事项

在使用MongoRepository的过程中,非模糊查询多配合使用Example/ExampleMatcher来完成工作,MongoRepository已经非常强大,常用功能如排序,分页都已实现,当然还有很多方法文中没有提到感兴趣的可以深入了解一下。如果MongoRepository能实现,尽量不要做冗余的工作,如果非要自定义方法才能实现,一定要符合Spring-Data的规则来定义方法名。这里有一个小坑需要注意一下,如果实体类中包含有基本数据类型的属性,那么在使用repository.find(Example)时,需要把这些属性忽略掉,因为基本数据类型在新建对象时会有默认值,这时如果你按照别的属性查找数据时,这些属性也会附带到条件里。比如上文代码中有一个根据用户名查找用户的方法,此时你期望的是在查询过程中只有用户名起作用,那么这时候就要加上下面的代码。如果不加,则条件中会多出age=0&createTime=0,查出的结果有误。

ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("age","createTime");
      Example<User> example = Example.of(user, matcher);
      

github地址如下

https://github.com/wppcoder/mongo-example.git

欢迎讨论交流,如有错误欢迎指正。
最后当次王婆卖波瓜,新项目FlowGate求star,欢迎交流和贡献,正在和linux 基金会谈,不久就会贡献到linux 基金会,目前是在公司下面开源
项目地址:https://github.com/vmware/flowgate
项目中文简介:https://mp.weixin.qq.com/s/8w7QImwns-WTI0_Hf6sblg

所有附件
该文章没有附件.
本文为原创文章,请注意保留出处!

热门文章

修复群晖Synology Drive client右键菜单缺失问题 本教程主要解决windows10右键菜单中没有SynologyDrive菜单的问题,整体思路是找到...修复群晖SynologyDriveclient右键菜单缺失问题 作者:Pastore Antonio
1812 浏览量
docker如何查看一个镜像内部的目录结构及其内部都有哪些文件 前言:有时候我们会在docker上下载一个镜像,或者是上传一个镜像到docker上,甚至有时候就是在...docker如何查看一个镜像内部的目录结构及其内部都有哪些文件 作者:Pastore Antonio
1791 浏览量
configure: error: Package requirements (oniguruma) were not met configure:error:Packagerequirements(oniguruma)...configure:error:Packagerequirements(oniguruma)werenotmet 作者:Pastore Antonio
1530 浏览量
Adobe Acrobat Pro 激活 这里记录了一些AdobeAcrobat的激活教程和组件。浏览量:1,683 作者:Pastore Antonio
1528 浏览量
追寻日出,找回自己 为什么我要去追寻日出?其实我是一个很懒的人,每次都起不来,直到有一次我在租房中睡到了大天亮,阳光照...追寻日出,找回自己 作者:Pastore Antonio
1506 浏览量