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.1
      database: dev-picker-db
      authentication-database: dev-picker-db
      port: 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 {
    @Id
    private 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 {

    @Resource
    private 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 {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private 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 {
    @Id
    private String id;
    @Indexed
    private 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;
    }

    @Deprecated
    public Integer getPage() {
        return page;
    }

    @Deprecated
    public 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;
    }

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于构建Java应用程序的框架,它能够简化开发过程,提高生产力。它通过提供一系列的开箱即用的特性和配置,允许我们快速构建可运行的、独立的Spring应用程序。 Druid是一个开源的Java数据库连接池框架,它提供了一组可扩展的API,用于管理和监控数据库连接。Druid具有优秀的性能和丰富的扩展功能,可以有效地管理大量的数据库连接。 MongoDB是一个开源的文档数据库,它使用JSON风格的文档格式存储数据。MongoDB具有高可用性、可扩展性和灵活的数据模型,适用于许多不同类型的应用程序。 Spring Boot与Druid和MongoDB的结合可以带来一些好处。首先,Druid可以作为Spring Boot应用程序的数据库连接池,提供高性能和高可用性的数据库连接管理。它可以监控和管理数据库连接的使用情况,避免连接泄漏和过多的连接创建。 其次,Spring BootMongoDB集成使得开发人员能够轻松地使用MongoDB作为应用程序的数据存储。Spring Boot提供了与MongoDB的无缝集成,简化了数据访问的配置和操作。 最后,Spring Boot、Druid和MongoDB集成可以帮助开发人员更好地应对大规模的数据存储和处理需求。Druid的连接池管理功能可以提高应用程序的性能和可靠性,而MongoDB的扩展性和灵活性可以满足不同类型的数据存储需求。 综上所述,Spring Boot、Druid和MongoDB的结合可以提供高性能、高可用性和灵活的数据存储和管理解决方案,适用于各种类型的Java应用程序开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值