spring boot 集成mongodb
引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId><version>2.2.0.RELEASE</version></dependency>
配置db:
spring:data:mongodb:host: 127.0.0.1database: dev-picker-dbauthentication-database: dev-picker-dbport: 27017
在实体类上添加 @Document 并指定集合名称 @Document(collection = "customer")
import com.person.common.utils.UUIDUitl;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;import java.util.Date;@AllArgsConstructor
@Data
@Document(collection = "customer")
public class Customer {@Idprivate String id;@Indexed /**索引列**/private String realName;private String mobile;private Address address;private Date createdTime;private Boolean member;public Customer() {id = UUIDUitl.generateLowerString(32);realName = "Han";mobile = "13770655999";address = new Address();createdTime = new Date();}public static class Address {private String aliasName;private String province;private String city;private String detail;public Address() {aliasName = "Home";province = "JiangSu";city = "NanJing";detail = "1865";}}public static Customer form(String realName, String mobile, Address address) {Customer customer = new Customer();customer.realName = realName;customer.mobile = mobile;customer.address = address;return customer;}public static Customer form(String realName, String mobile, Address address, Boolean isMember) {Customer customer = new Customer();customer.realName = realName;customer.mobile = mobile;customer.address = address;customer.member = isMember;return customer;}}
编写测试类
import com.bmyg.api.mongo.Customer;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource;@RequestMapping("/uncontrol/mongo")
@RestController
public class MongoDBController {@Resourceprivate MongoTemplate mongoTemplate;@GetMapping("/test")public String getMongoDBName() {Customer customer = new Customer();mongoTemplate.insert(customer);return mongoTemplate.getDb().getName();}}
结果:
其他查询:
package com.test.api;import com.alibaba.fastjson.JSON;
import com.test.api.mongo.Customer;
import com.test.api.mongo.CustomerRepository;
import com.test.api.mongo.CustomerVo;
import com.test.api.mongo.PageResult;
import com.mongodb.client.ListIndexesIterable;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;@RequestMapping("/uncontrol/mongo")
@RestController
public class MongoDBController {@Resourceprivate MongoTemplate mongoTemplate;@Resourceprivate CustomerRepository customerRepository;//给customer集合的某个字段创建索引@GetMapping("/crtIdx")public String createIndex(@RequestParam String key) {Index index = new Index(key, Sort.Direction.ASC);mongoTemplate.indexOps("customer").ensureIndex(index);return "ok";}//获取所有集合@GetMapping("/coll")public Set<String> index() {return mongoTemplate.getCollectionNames();}//插入@GetMapping("/insert")public String insert() {Customer customer = new Customer();mongoTemplate.insert(customer);return mongoTemplate.getDb().getName();}//查询@PostMapping("/query")public String query(@RequestBody Customer cus) {//查询所有List<Customer> result = mongoTemplate.findAll(Customer.class);System.out.println("查询所有" + JSON.toJSONString(result));//通过ID 查询Customer byId = mongoTemplate.findById(cus.getId(), Customer.class);System.out.println("通过ID 查询" + JSON.toJSONString(byId));Query query = new Query(Criteria.where("realName").is(cus.getRealName()));//条件-精确查询,返回第一条数据,没有条件 依旧会查询数据,但是返回第一条Customer findOne = mongoTemplate.findOne(query, Customer.class);System.out.println("条件-精确查询,返回第一条数据" + JSON.toJSONString(findOne));//条件-精确查询,返回所有数据---没有条件 依旧会查询数据,返回所有List<Customer> findList = mongoTemplate.find(query, Customer.class);System.out.println("条件-精确查询,返回所有数据" + JSON.toJSONString(findList));return JSON.toJSONString(result);}//删除@PostMapping("/del")public String del(@RequestBody Customer cus) {Query query = new Query(Criteria.where("realName").is(cus.getRealName()));mongoTemplate.remove(query, Customer.class);return mongoTemplate.getDb().getName();}//查询所有索引@PostMapping("/all-idx")public String getIndexAll() {// 获取集合中所有列表---import org.bson.Document;ListIndexesIterable<Document> indexList =mongoTemplate.getCollection("customer").listIndexes();StringBuilder sb = new StringBuilder();// 获取集合中全部索引信息for (Document document : indexList) {sb.append(document + "/r/n");}return sb.toString();}//模糊查询@PostMapping("/like-query")public String likequery(@RequestBody Customer cus) {//模糊查询Query queryLike = new Query(Criteria.where("realName").regex(".*" + cus.getRealName() + ".*"));List<Customer> queryLikeResult = mongoTemplate.find(queryLike, Customer.class);System.out.println(queryLikeResult);return JSON.toJSONString(queryLikeResult);}//多条件查询 and@PostMapping("/query-and")public String manyMatchAnd(@RequestBody Customer cus) {//多条件查询Criteria criteriaUserName = Criteria.where("realName").is(cus.getRealName());Criteria criteriaPassWord = Criteria.where("mobile").is(cus.getMobile());// 创建条件对象,将上面条件进行 AND 关联Criteria criteria = new Criteria().andOperator(criteriaUserName, criteriaPassWord);Query queryLike = new Query(criteria);List<Customer> queryLikeResult = mongoTemplate.find(queryLike, Customer.class);return JSON.toJSONString(queryLikeResult);}//多条件查询 or@PostMapping("/query-or")public String manyMatchOr(@RequestBody Customer cus) {Criteria criteriaUserName = Criteria.where("realName").is(cus.getRealName());Criteria criteriaPassWord = Criteria.where("mobile").is(cus.getMobile());// 创建条件对象,将上面条件进行 OR 关联Criteria criteria = new Criteria().orOperator(criteriaUserName, criteriaPassWord);Query queryor = new Query(criteria);List<Customer> queryLikeResult = mongoTemplate.find(queryor, Customer.class);return JSON.toJSONString(queryLikeResult);}//多条件查询 in@PostMapping("/query-in")public String findByInCondition() {// 设置查询条件参数List<String> names = Arrays.asList("Ma", "liu", "li");// 创建条件-- 创建条件,in 后面是list 集合Criteria criteria = Criteria.where("realName").in(names);// 创建查询对象,然后将条件对象添加到其中Query queryIn = new Query(criteria);List<Customer> result = mongoTemplate.find(queryIn, Customer.class);return JSON.toJSONString(result);}//根据【逻辑运算符】查询集合中的文档数据@PostMapping("/query-gt")public String findByGt() {int min = 20;int max = 35;Criteria criteria = Criteria.where("age").gt(min).lte(max);// 创建查询对象,然后将条件对象添加到其中Query queryGt = new Query(criteria);List<Customer> result = mongoTemplate.find(queryGt, Customer.class);return JSON.toJSONString(result);}//根据【正则表达式】查询集合中的文档数据@PostMapping("/query-regex")public String findByRegex() {String regex = "^张*";Criteria criteria = Criteria.where("realName").regex(regex);// 创建查询对象,然后将条件对象添加到其中Query queryRegex = new Query(criteria);List<Customer> result = mongoTemplate.find(queryRegex, Customer.class);return JSON.toJSONString(result);}//更新@PostMapping("/update")public String update(@RequestBody Customer cus) {Query query = new Query(Criteria.where("mobile").is(cus.getMobile()));Update update = new Update().set("realName", cus.getRealName());mongoTemplate.updateMulti(query, update, Customer.class);return mongoTemplate.getDb().getName();}// 分页查询---逻辑没问题 序列化有问题!!!!!!!!!!!!!!!!!@PostMapping("/query-page")public PageResult<Customer> queryPage(@RequestBody CustomerVo customerVo) {Customer cus = new Customer();BeanUtils.copyProperties(customerVo, cus);Query queryLike = new Query(Criteria.where("realName").regex(".*" + cus.getRealName() + ".*"));long total = mongoTemplate.count(queryLike, Customer.class);Integer skip = (customerVo.getPageNo() - 1) * customerVo.getPageSize();queryLike.skip(skip).limit(customerVo.getPageSize());queryLike.with(Sort.by(Sort.Order.desc("createdTime")));List<Customer> findList = mongoTemplate.find(queryLike, Customer.class);return PageResult.pageResult(customerVo.getPageNo(), customerVo.getPageSize(), (int) total, findList);}}
其他:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.person.common.utils.UUIDUitl;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;import java.util.Date;@AllArgsConstructor
@Data
@Document(collection = "customer")
public class Customer {@Idprivate String id;@Indexedprivate String realName;private String mobile;@JsonIgnoreProperties(ignoreUnknown = true)private Address address;private Date createdTime;private Boolean member;private int age;public Customer() {id = UUIDUitl.generateLowerString(32);realName = "Han";mobile = "13770655999";address = new Address();createdTime = new Date();age = 18;}public static class Address {private String aliasName;private String province;private String city;private String detail;public Address() {aliasName = "Home";province = "JiangSu";city = "NanJing";detail = "1865";}}public static Customer form(String realName, String mobile, Address address) {Customer customer = new Customer();customer.realName = realName;customer.mobile = mobile;customer.address = address;return customer;}public static Customer form(String realName, String mobile, Address address, Boolean isMember) {Customer customer = new Customer();customer.realName = realName;customer.mobile = mobile;customer.address = address;customer.member = isMember;return customer;}}
import lombok.AllArgsConstructor;
import lombok.Data;import java.util.Date;/**** @version JDK 11* @className CustomerVo* @description TODO*/@AllArgsConstructor
@Data
public class CustomerVo {private String id;private String realName;private String mobile;private Date createdTime;private Boolean member;private int age;private Integer pageNo;private Integer pageSize;}
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.validator.constraints.Range;import javax.validation.constraints.NotNull;
import java.io.Serializable;@Data
@ApiModel
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
public class PageQuery implements Serializable {@ApiModelProperty(value = "页码,默认1", example = "1")@NotNull(message = "页码不能为空")@Range(min = 1, message = "页码不正确")protected Integer pageNo = 1;@ApiModelProperty(value = "每页条数, 默认10", example = "10")@NotNull(message = "每页条数不能为空")protected Integer pageSize = 10;/*** 偏移*/@ApiModelProperty(hidden = true)protected Integer offset;public Integer getOffset() {return (getPageNo() - 1) * getPageSize();}public Integer getPageNo() {return pageNo == null ? 1 : pageNo;}public Integer getPageSize() {return pageSize == null ? 10 : pageSize;}
}
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;import java.io.Serializable;
import java.util.Collections;
import java.util.List;@Data
@ApiModel(description = "分页数据返回模型")
public class PageResult<T> implements Serializable {@ApiModelProperty(value = "当前页 - 和PageQuery保持统一")private Integer pageNo;@Deprecated@ApiModelProperty(value = "当前页", hidden = true)private Integer page;@ApiModelProperty(value = "每页条数")private Integer pageSize;@ApiModelProperty(value = "总记录数")private Integer total;@ApiModelProperty(value = "查询数据")private List<T> list;public Integer getPageNo() {return pageNo;}public void setPageNo(Integer pageNo) {this.pageNo = pageNo;this.page = pageNo;}@Deprecatedpublic Integer getPage() {return page;}@Deprecatedpublic void setPage(Integer page) {this.page = page;this.pageNo = page;}public static <T> PageResult<T> pageResult(Integer page, Integer pageSize, Integer total, List<T> list) {PageResult<T> pageResult = new PageResult<T>();pageResult.setPage(page);pageResult.setPageNo(page);pageResult.setPageSize(pageSize);pageResult.setList(list);pageResult.setTotal(total);return pageResult;}public static <T> PageResult<T> pageResult(PageQuery query, Integer total, List<T> list) {return pageResult(query.getPageNo(), query.getPageSize(), total, list);}public static <T> PageResult<T> pageResult(PageQuery query, long total, List<T> list) {return pageResult(query.getPageNo(), query.getPageSize(), (int) total, list);}// public static <T> PageResult<T> pageResultLimit( PageQuery query, long total, List<T> list ) {
// if (total>10000L){
// total=10000L;
// }
// return pageResult(query.getPageNo(), query.getPageSize(), (int) total, list);
// }public static <T> PageResult<T> empty(PageQuery query) {return pageResult(query, 0, Collections.emptyList());}/*** 获取总页数** @return 总页数*/@JsonIgnore@ApiModelProperty(hidden = true)public Integer getPages() {if (getPageSize() == 0) {return 0;}int pages = getTotal() / getPageSize();if (getTotal() % getPageSize() != 0) {pages++;}return pages;}}