依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
   </dependency>

代码

SimpleMongoService

package com.baba.security.auth2.service;

import com.baba.security.auth2.entity.RangeEntity;

import java.util.List;
import java.util.Map;

/**
 * @Author wulongbo
 * @Date 2022/1/19 15:28
 * @Version 1.0
 */
public interface SimpleMongoService<T> {

    void createCollection(String name);

    String createIndex(String collectionName, String filedName);

    List<String> getAllIndexes(String collectionName);

    void insert(T info, String collectionName);

    void insertMulti(List<T> infos, String collectionName);

    void updateById(String id, String collectionName, T info);

    void deleteById(String id, Class<T> clazz, String collectionName);

    T selectById(String id, Class<T> clazz, String collectionName);

    List<T> selectList(String collectName, Class<T> clazz);

    List<T> selectList(String collectName, Class<T> clazz, Integer currentPage, Integer pageSize);

    List<T> selectByCondition(String collectName, Map<String, Object> conditions, Class<T> clazz, Integer currentPage, Integer pageSize);

 Long selectCountByCondition(String collectName, Map<String, RangeEntity> range, Map<String, Object> conditions, Map<String, List<String>> inList);

    PageInfo<T> selectPageByCondition(String collectName, Map<String, RangeEntity> range, Map<String, Object> conditions, Map<String, List<String>> inList,Class<T> clazz, Integer currentPage, Integer pageSize);

    List<T> selectByCondition(String collectName, Map<String, RangeEntity> range, Map<String, Object> conditions, Map<String, List<String>> inList, Class<T> clazz, Integer currentPage, Integer pageSize);


}

SimpleMongoServiceImpl

package com.baba.security.auth2.service.impl.mongo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baba.security.auth2.entity.MongoBaseInfo;
import com.baba.security.auth2.entity.RangeEntity;
import com.baba.security.auth2.service.SimpleMongoService;
import com.mongodb.client.ListIndexesIterable;
import com.mongodb.client.model.IndexOptions;
import com.mongodb.client.model.Indexes;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author wulongbo
 * @Date 2022/1/19 15:20
 * @Version 1.0
 * 简单的mongodb使用接口
 */

@Service
public class SimpleMongoServiceImpl<T extends MongoBaseInfo> implements SimpleMongoService<T> {

    /**
     * 注入template,减少重复代码
     */
    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 功能描述: 创建一个集合
     * 同一个集合中可以存入多个不同类型的对象,我们为了方便维护和提升性能,
     * 后续将限制一个集合中存入的对象类型,即一个集合只能存放一个类型的数据
     *
     * @param name 集合名称,相当于传统数据库的表名
     * @return:void
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 17:27
     */
    @Override
    public void createCollection(String name) {
        mongoTemplate.createCollection(name);
    }

    /**
     * 功能描述: 创建索引
     * 索引是顺序排列,且唯一的索引
     *
     * @param collectionName 集合名称,相当于关系型数据库中的表名
     * @param filedName      对象中的某个属性名
     * @return:java.lang.String
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 16:13
     */
    @Override
    public String createIndex(String collectionName, String filedName) {
        //配置索引选项
        IndexOptions options = new IndexOptions();
        // 设置为唯一
        options.unique(true);
        //创建按filedName升序排的索引
        return mongoTemplate.getCollection(collectionName).createIndex(Indexes.ascending(filedName), options);
    }


    /**
     * 功能描述: 获取当前集合对应的所有索引的名称
     *
     * @param collectionName
     * @return:java.util.List<java.lang.String>
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 16:46
     */
    @Override
    public List<String> getAllIndexes(String collectionName) {
        ListIndexesIterable<Document> list = mongoTemplate.getCollection(collectionName).listIndexes();
        //上面的list不能直接获取size,因此初始化arrayList就不设置初始化大小了
        List<String> indexes = new ArrayList<>();
        for (Document document : list) {
            document.entrySet().forEach((key) -> {
                //提取出索引的名称
                if (key.getKey().equals("name")) {
                    indexes.add(key.getValue().toString());
                }
            });
        }
        return indexes;
    }

    /**
     * 功能描述: 往对应的集合中插入一条数据
     *
     * @param info           存储对象
     * @param collectionName 集合名称
     * @return:void
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 16:46
     */
    @Override
    public void insert(T info, String collectionName) {
        mongoTemplate.insert(info, collectionName);
    }

    /**
     * 功能描述: 往对应的集合中批量插入数据,注意批量的数据中不要包含重复的id
     *
     * @param infos 对象列表
     * @return:void
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 16:47
     */
    @Override
    public void insertMulti(List<T> infos, String collectionName) {
        mongoTemplate.insert(infos, collectionName);
    }

    /**
     * 功能描述: 使用索引信息精确更改某条数据
     *
     * @param id             唯一键
     * @param collectionName 集合名称
     * @param info           待更新的内容
     * @return:void
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 18:42
     */
    @Override
    public void updateById(String id, String collectionName, T info) {
        Query query = new Query(Criteria.where("id").is(id));
        Update update = new Update();
        String str = JSON.toJSONString(info);
        JSONObject jQuery = JSON.parseObject(str);
        jQuery.forEach((key, value) -> {
            //因为id相当于传统数据库中的主键,这里使用时就不支持更新,所以需要剔除掉
            if (!key.equals("id")) {
                update.set(key, value);
            }
        });
        mongoTemplate.updateMulti(query, update, info.getClass(), collectionName);
    }

    /**
     * 功能描述: 根据id删除集合中的内容
     *
     * @param id             序列id
     * @param collectionName 集合名称
     * @param clazz          集合中对象的类型
     * @return:void
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 16:47
     */
    @Override
    public void deleteById(String id, Class<T> clazz, String collectionName) {
        // 设置查询条件,当id=#{id}
        Query query = new Query(Criteria.where("id").is(id));
        // mongodb在删除对象的时候会判断对象类型,如果你不传入对象类型,只传入了集合名称,它是找不到的
        // 上面我们为了方便管理和提升后续处理的性能,将一个集合限制了一个对象类型,所以需要自行管理一下对象类型
        // 在接口传入时需要同时传入对象类型
        mongoTemplate.remove(query, clazz, collectionName);
    }

    /**
     * 功能描述: 根据id查询信息
     *
     * @param id             注解
     * @param clazz          类型
     * @param collectionName 集合名称
     * @return:java.util.List<T>
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/20 16:47
     */
    @Override
    public T selectById(String id, Class<T> clazz, String collectionName) {
        // 查询对象的时候,不仅需要传入id这个唯一键,还需要传入对象的类型,以及集合的名称
        return mongoTemplate.findById(id, clazz, collectionName);
    }

    /**
     * 功能描述: 查询列表信息
     * 将集合中符合对象类型的数据全部查询出来
     *
     * @param collectName 集合名称
     * @param clazz       类型
     * @return:java.util.List<T>
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/21 10:38
     */
    @Override
    public List<T> selectList(String collectName, Class<T> clazz) {
        return selectList(collectName, clazz, null, null);
    }

    /**
     * 功能描述: 分页查询列表信息
     *
     * @param collectName 集合名称
     * @param clazz       对象类型
     * @param currentPage 当前页码
     * @param pageSize    分页大小
     * @return:java.util.List<T>
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/21 10:38
     */
    @Override
    public List<T> selectList(String collectName, Class<T> clazz, Integer currentPage, Integer pageSize) {
        //设置分页参数
        Query query = new Query();
        //设置分页信息
        if (!ObjectUtils.isEmpty(currentPage) && ObjectUtils.isEmpty(pageSize)) {
            query.limit(pageSize);
            query.skip(pageSize * (currentPage - 1));
        }
        return mongoTemplate.find(query, clazz, collectName);
    }


    /**
     * 功能描述: 根据条件查询集合
     *
     * @param collectName 集合名称
     * @param conditions  查询条件,目前查询条件处理的比较简单,仅仅做了相等匹配,没有做模糊查询等复杂匹配
     * @param clazz       对象类型
     * @param currentPage 当前页码
     * @param pageSize    分页大小
     * @return:java.util.List<T>
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/21 10:48
     */
    @Override
    public List<T> selectByCondition(String collectName, Map<String, Object> conditions, Class<T> clazz, Integer currentPage, Integer pageSize) {
        if (ObjectUtils.isEmpty(conditions)) {
            return selectList(collectName, clazz, currentPage, pageSize);
        } else {
            //设置分页参数
            Query query = new Query();
            query.limit(pageSize);
            query.skip(currentPage);
            // 往query中注入查询条件
            conditions.forEach((key, value) -> query.addCriteria(Criteria.where(key).is(value)));
            return mongoTemplate.find(query, clazz, collectName);
        }
    }

    /**
     * 功能描述: 根据条件范围查询总记录数
     *
     * @param collectName 集合名称
     * @param conditions  查询条件
     * @return:java.util.List<T>
     * @since: v1.0
     * @Author:wangcanfeng
     * @Date: 2019/3/21 10:48
     */
    @Override
    public Long selectCountByCondition(String collectName, Map<String, RangeEntity> range, Map<String, Object> conditions, Map<String, List<String>> inList) {
        if (ObjectUtils.isEmpty(conditions) && ObjectUtils.isEmpty(range)&& ObjectUtils.isEmpty(inList)) {
            return mongoTemplate.getCollection(collectName).estimatedDocumentCount();
        } else {
            Query query = new Query();
            //设置分页参数
            // 往query中注入查询条件
            if (!ObjectUtils.isEmpty(conditions)) {
                conditions.forEach((key, value) -> query.addCriteria(Criteria.where(key).is(value)));
            }
            if (!ObjectUtils.isEmpty(range)) {
                range.forEach((key, value) -> query.addCriteria(Criteria.where(key).gte(value.getGte()).lte(value.getLt())));            }
            if (!ObjectUtils.isEmpty(inList)) {
                inList.forEach((key, value) ->query.addCriteria(Criteria.where(key).in(value)));
            }
            return mongoTemplate.count(query, collectName);
        }
    }

    /**
     * 条件分页查询
     * @param collectName
     * @param range
     * @param conditions
     * @param inList
     * @param clazz
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<T> selectPageByCondition(String collectName, Map<String, RangeEntity> range, Map<String, Object> conditions,
                                 Map<String, List<String>> inList, Class<T> clazz, Integer currentPage, Integer pageSize) {
        List<T> list = this.selectByCondition(collectName, range, conditions,inList, clazz, currentPage, pageSize);
        Long count = this.selectCountByCondition(collectName, range, conditions,inList);
        PageInfo<T> pageInfo = new PageInfo();
        pageInfo.setResultList(list);
        pageInfo.setPageNum(currentPage);
        pageInfo.setPageSize(pageSize);
        pageInfo.setTotalRecord(count.intValue());
        return pageInfo;
    }

    /**
     * 功能描述: 根据条件范围查询集合
     *
     * @param collectName 集合名称
     * @param range       范围条件
     * @param conditions  查询条件
     * @param clazz       对象类型
     * @param currentPage 当前页码
     * @param pageSize    分页大小
     * @return:java.util.List<T>
     */
    @Override
    public List<T> selectByCondition(String collectName, Map<String, RangeEntity> range, Map<String, Object> conditions,
                                     Map<String, List<String>> inList, Class<T> clazz, Integer currentPage, Integer pageSize) {
        if (ObjectUtils.isEmpty(conditions) && ObjectUtils.isEmpty(range) && ObjectUtils.isEmpty(inList)) {
            return selectList(collectName, clazz, currentPage, pageSize);
        }
        Query query = new Query();
        //设置分页参数
        // 往query中注入查询条件
        if (!ObjectUtils.isEmpty(conditions)) {
//            conditions.forEach((key, value) -> criatira1.and(key).is(value));
            conditions.forEach((key, value) -> query.addCriteria(Criteria.where(key).is(value)));
        }
        if (!ObjectUtils.isEmpty(range)) {
//            range.forEach((key, value) -> criatira1.and(key).gte(value.getGte()).lte(value.getLt()));
            range.forEach((key, value) -> query.addCriteria(Criteria.where(key).gte(value.getGte()).lte(value.getLt())));
        }
        if (!ObjectUtils.isEmpty(inList)) {
            inList.forEach((key, value) ->query.addCriteria(Criteria.where(key).in(value)));
        }
        if (!ObjectUtils.isEmpty(currentPage) && ObjectUtils.isEmpty(pageSize)) {
            query.limit(pageSize);
            query.skip(pageSize * (currentPage - 1));
        }
        return mongoTemplate.find(query, clazz, collectName);
    }






MongoBaseInfo

package com.baba.security.auth2.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @Author wulongbo
 * @Date 2022/1/19 15:27
 * @Version 1.0
 */

@Getter
@Setter
@ToString
public class MongoBaseInfo {
    private String id;
}

PageInfo

package com.baba.security.auth2.utils;

import java.util.List;

/**
 * @Author wulongbo
 * @Date 2021/3/20 10:42
 * @Version 1.0
 */
public class PageInfo<T> {
    protected int pageNum = 1;//页码
    protected int pageSize = 10;//返回条数
    protected long totalRecord = -1;//总记录数
    protected int totalPage = -1;//总页数
    protected int startIndex = 0; //第几条记录开始
    protected List<T> resultList;//结果集

    public PageInfo() {
    }

    public PageInfo(int pageSize, int pageNum) {
        this.pageSize = pageSize;
        this.pageNum = pageNum;
    }

    public PageInfo(Integer pageNum) {
        if (pageNum != null) {
            this.pageNum = pageNum.intValue();
        }
    }

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
        setPageSize(this.pageSize);
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
        computeTotalPage();
    }

    public long getTotalRecord() {
        return totalRecord;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalRecord(long totalRecord) {
        this.totalRecord = totalRecord;
        computeTotalPage();
    }

    public int getStartIndex() {
        return (pageNum - 1) * pageSize;
    }

    protected void computeTotalPage() {
        if (getPageSize() > 0 && getTotalRecord() > -1) {
            this.totalPage = (int) (getTotalRecord() % getPageSize() == 0 ? getTotalRecord()
                    / getPageSize()
                    : getTotalRecord() / getPageSize() + 1);
        }
        if (this.totalPage == 0) {
            this.totalPage = 1;
        }
    }

    public List<T> getResultList() {
        return resultList;
    }

    public void setResultList(List<T> resultList) {
        this.resultList = resultList;
    }
}

测试类

import com.baba.security.auth2.Application;
import com.baba.security.auth2.entity.*;
import com.baba.security.auth2.service.SimpleMongoService;
import com.baba.security.auth2.service.SourceService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Profile;
import java.util.*;    
@SpringBootTest(classes = Application.class)
@Profile(value = "dev")
@RunWith(SpringRunner.class)
public class ApiTest {
@Autowired
    private SimpleMongoService simpleMongoService;

    /**
     * 创建集合
     *
     * @throws Exception
     */
    @Test
    public void createCollection() {
        simpleMongoService.createCollection("wulongbo");
    }

    /**
     * 往对应的集合中插入一条数据
     *
     * @throws Exception
     */
    @Test
    public void insert() {
        RoleTest role = new RoleTest();
        role.setRoleName("角色名称");
        role.setCreateTime(System.currentTimeMillis());
        role.setUpdateTime(System.currentTimeMillis());
        role.setUserId(1L);
        role.setRoleDesc("角色描述");
        simpleMongoService.insert(role, "wulongbo");
    }

    /**
     * 往对应的集合中批量插入一条数据
     *
     * @throws Exception
     */
    @Test
    public void batchInsert() {
        List<RoleTest> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            RoleTest role = new RoleTest();
            role.setRoleName("角色名称" + 7);
            role.setCreateTime(System.currentTimeMillis() + i);
            role.setUpdateTime(System.currentTimeMillis() + i);
            role.setUserId(1L + i);
            role.setRoleDesc("角色描述" + 7);
            list.add(role);
        }
        simpleMongoService.insertMulti(list, "wulongbo");
    }

    /**
     * 根据id删除集合中的内容
     *
     * @throws Exception
     */
    @Test
    public void deleteById() {
        simpleMongoService.deleteById("61e8b1e36fad7769c0015fff", RoleTest.class, "wulongbo");
    }

    /**
     * 根据id查询信息
     *
     * @throws Exception
     */
    @Test
    public void selectById() {
        RoleTest roleTest = (RoleTest) simpleMongoService.selectById("61e8b1e36fad7769c0015ffd", RoleTest.class, "wulongbo");
        System.out.println(roleTest.toString());
    }


    /**
     * 查询列表信息
     *
     * @throws Exception
     */
    @Test
    public void selectList() {
        List<RoleTest> roleTest = simpleMongoService.selectList("wulongbo", RoleTest.class);
        System.out.println(roleTest.toString());
    }

    /**
     * 分页查询列表信息
     *
     * @throws Exception
     */
    @Test
    public void selectList1() {
        List<RoleTest> roleTest = simpleMongoService.selectList("wulongbo", RoleTest.class, 1, 10);
        System.out.println(roleTest.toString());
    }

    /**
     * 根据条件查询集合
     *
     * @throws Exception
     */
    @Test
    public void selectByCondition() {
        Map<String, Object> map = new HashMap();
        map.put("createTime", 1642642710124L);
        map.put("roleDesc", "角色描述7");
        List<RoleTest> roleTest = simpleMongoService.selectByCondition("wulongbo", map, RoleTest.class, 1, 10);
        System.out.println(roleTest.toString());
    }

    /**
     * 根据范围条件查询集合
     *
     * @throws Exception
     */
    @Test
    public void selectByCondition1() {
        Map<String, Object> map1 = new HashMap();
        map1.put("roleDesc", "角色描述7");
        Map<String, RangeEntity> map = new HashMap();
        RangeEntity r = new RangeEntity();
        r.setLt(1642642710130L);
        r.setGte(1642648687019L);
        map.put("createTime",r);
        List<RoleTest> roleTest = simpleMongoService.selectByCondition("wulongbo", null,map1, RoleTest.class, 1, 10);
        System.out.println(roleTest.toString());
    }
}

RangeEntity

package com.baba.security.auth2.entity;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @Author wulongbo
 * @Date 2022/1/20 10:07
 * @Version 1.0
 */

@Getter
@Setter
@ToString
public class RangeEntity {

    private Object lt;

    private Object gte;

}

isWulongbo
228 声望26 粉丝

在人生的头三十年,你培养习惯,后三十年,习惯铸就你