SpringBoot 整合MongoDB的基本操作

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/LiaoHongHB/article/details/83900867

话不多说,直接上代码(转载务必说明出处  https://blog.csdn.net/LiaoHongHB/article/details/83900867):

public class MongoDaoImpl<T> implements MongoDao<T> {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MongoDaoImpl.class);

    @Autowired
    protected MongoTemplate mongoTemplate;

    /**
     * clazz
     */
    private Class<T> clazz;

    public MongoDaoImpl() {
        try {
            ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
            clazz = (Class<T>) type.getActualTypeArguments()[0];
            LOGGER.info("reflect Class:{}", clazz);
        } catch (Exception e) {
            LOGGER.error("MongoDaoImpl reflection happen error:{}", e);
        }
    }

    /**
     * 创建对象
     *
     * @param t
     */
    @Override
    public void save(T t) throws BbsException {
        try {
            if (t != null) {
                mongoTemplate.save(t);
            } else {
                throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s save error for MongoDB:", JSON.toJSONString(t)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
        }
    }

    /**
     * 批量保存
     *
     * @param entities
     */
    @Override
    public void saveBatch(List<T> entities) throws BbsException {
        try {
            if (entities != null && entities.size() > 0) {
                mongoTemplate.insert(entities, clazz);
            } else {
                throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s saveBatch error for MongoDB:{}", JSON.toJSONString(entities)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
        }
    }

    /**
     * 删除对象
     *
     * @param id
     */
    @Override
    public void delete(Serializable id) throws BbsException {
        try {
            if (id != null) {
                Query query = new Query(Criteria.where("id").is(id));
                mongoTemplate.remove(query, clazz);
            } else {
                throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s delete error for MongoDB:{}", id), e);
            throw new BbsException(new RestFulVO(PostRetEnum.SAVA_DATA_EXCPTION));
        }
    }

    /**
     * 更新对象
     *
     * @param t
     */
    @Override
    public void update(T t) throws BbsException {
        try {
            if (t != null) {
                Method getId = ReflectionUtils.findMethod(clazz, "getId");
                Object id = ReflectionUtils.invokeMethod(getId, t);
                Query query = new Query(Criteria.where("id").is(id));
                Update update = new Update();
                ReflectionUtils.doWithFields(clazz, field -> {
                    ReflectionUtils.makeAccessible(field);
                    if (!"id".equals(field.getName()) && field.get(t) != null) {
                        update.set(field.getName(), field.get(t));
                    }
                });
                mongoTemplate.updateFirst(query, update, clazz);
            } else {
                throw new BbsException(new RestFulVO(PostRetEnum.BBS_UPDATE_FAULT));
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s update error for MongoDB:{}", JSON.toJSONString(t)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_UPDATE_FAULT));
        }
    }

    @Override
    public void updateOneFieldBatch(T t, Map<String, Object> queryCondition, String updateKey, Object updateValue) throws BbsException {
        try {
            if (t != null) {
                Query query = new Query();
                if (queryCondition != null) {
                    queryCondition.forEach((k, v) -> {
                        query.addCriteria(Criteria.where(k).is(v));
                    });
                }
                //Update update = Update.update(queryCondition, queryValue).set(updateKey, updateValue);
                Update update = new Update();
                update.set(updateKey, updateValue);
                mongoTemplate.updateMulti(query, update, clazz);
            } else {
                throw new BbsException(new RestFulVO(PostRetEnum.BBS_UPDATE_FAULT));
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s updateOneFildBatch error for MongoDB:{}", JSON.toJSONString(t)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_UPDATE_FAULT));
        }
    }


    /**
     * 由id查询对象
     *
     * @param id
     * @return
     */
    @Override
    public T findById(Serializable id) throws BbsException {
        return this.findById(id, null);
    }

    /**
     * 由id查询对象,排除字段
     *
     * @param id
     * @param excludeFields
     * @return
     */
    @Override
    public T findById(Serializable id, List<String> excludeFields) throws BbsException {
        try {
            if (id != null) {
                Query query = new Query(Criteria.where("id").is(id));
                if (excludeFields != null && excludeFields.size() > 0) {
                    Field fields = query.fields();
                    excludeFields.stream().forEach(t -> fields.exclude(t));
                }
                return mongoTemplate.findOne(query, clazz);
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s findById error for MongoDB:{}", id), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_QUERY_FAULT));
        }
        return null;
    }

    /**
     * 搜索关键字,带分页、排序和排除字段
     *
     * @param pageNum
     * @param pageSize
     * @param condition
     * @param field
     * @param keyword
     * @param sort
     * @param excludeFields
     * @return
     */
    @Override
    public List<T> search(int pageNum, int pageSize, Map<String, Object> condition, String field, String keyword, Sort sort, List<String> excludeFields) throws BbsException {
        try {
            if (!StringUtils.isEmpty(keyword) && !StringUtils.isEmpty(field)) {
                Query query = new Query(Criteria.where(field).regex(keyword));
                if (condition != null) {
                    condition.forEach((k, v) -> {
                        query.addCriteria(Criteria.where(k).is(v));
                    });
                }
                if (excludeFields != null && excludeFields.size() > 0) {
                    Field fields = query.fields();
                    excludeFields.stream().forEach(t -> fields.exclude(t));
                }
                if (sort != null) {
                    query.with(sort);
                }
                query.skip((pageNum - 1) * pageSize).limit(pageSize);
                return mongoTemplate.find(query, clazz);
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s search error for MongoDB:{}", keyword), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_QUERY_FAULT));
        }
        return null;
    }

    /**
     * 搜索关键字,带分页、排序
     *
     * @param pageNum
     * @param pageSize
     * @param field
     * @param keyword
     * @param sort
     * @return
     */
    @Override
    public List<T> search(int pageNum, int pageSize, String field, String keyword, Sort sort) throws BbsException {
        return this.search(pageNum, pageSize, null, field, keyword, sort, null);
    }

    /**
     * 搜索关键字,带分页
     *
     * @param pageNum
     * @param pageSize
     * @param field
     * @param keyword
     * @return
     */
    @Override
    public List<T> search(int pageNum, int pageSize, String field, String keyword) throws BbsException {
        return this.search(pageNum, pageSize, null, field, keyword, null, null);
    }

    /**
     * 统计搜索的总记录数
     *
     * @param field
     * @param keyword
     * @param condition
     * @return
     */
    @Override
    public Long searchTotal(Map<String, Object> condition, String field, String keyword) throws BbsException {
        try {
            if (!StringUtils.isEmpty(keyword) && !StringUtils.isEmpty(field)) {
                Query query = new Query(Criteria.where(field).regex(keyword));
                if (condition != null) {
                    condition.forEach((k, v) -> {
                        query.addCriteria(Criteria.where(k).is(v));
                    });
                }
                return mongoTemplate.count(query, clazz);
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s searchTotal error for MongoDB:{}", keyword), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_QUERY_FAULT));
        }
        return null;
    }

    /**
     * 按对象条件查询
     *
     * @param condition
     * @return
     */
    @Override
    public List<T> findByCondition(Map<String, Object> condition) throws BbsException {
        return this.findByCondition(condition, null, null);
    }

    /**
     * 按对象条件查询,排序
     *
     * @param condition
     * @return
     */
    @Override
    public List<T> findByCondition(Map<String, Object> condition, Sort sort) throws BbsException {
        return this.findByCondition(condition, null, sort);
    }

    /**
     * 按对象条件查询,排除字段
     *
     * @param condition
     * @param excludeFields
     * @return
     */
    @Override
    public List<T> findByCondition(Map<String, Object> condition, List<String> excludeFields, Sort sort) throws BbsException {
        try {
            if (condition != null) {
                Query query = new Query();
                condition.forEach((k, v) -> {
                    query.addCriteria(Criteria.where(k).is(v));
                });
                if (excludeFields != null && excludeFields.size() > 0) {
                    Field fields = query.fields();
                    excludeFields.stream().forEach(t -> fields.exclude(t));
                }
                if (sort != null) {
                    query.with(sort);
                }
                return mongoTemplate.find(query, clazz);
            }
        } catch (Exception e) {
            LOGGER.error(String.format("%s findByExample error for MongoDB:{}", JSON.toJSONString(condition)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_QUERY_FAULT));
        }
        return new ArrayList<>();
    }

    /**
     * 带条件分页排序查询
     *
     * @param pageNum
     * @param pageSize
     * @param condition
     * @return
     */
    @Override
    public List<T> pageList(int pageNum, int pageSize, Map<String, Object> condition, Sort sort) throws BbsException {
        return this.pageList(pageNum, pageSize, condition, sort, null, null);
    }

    /**
     * 查询分组之后的总记录数
     *
     * @param criteria1
     * @param criteria2
     * @param field1
     * @param field2
     * @param collectionName
     * @return
     * @throws BbsException
     */
    @Override
    public AggregationResults<T> aggregation(Criteria criteria1,Criteria criteria2, String field1, String field2, String collectionName) throws BbsException {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria1),
                Aggregation.match(criteria2),
                Aggregation.group(field1, field2)
        );
        return mongoTemplate.aggregate(aggregation, collectionName, clazz);
    }

    /**
     * 分组查询
     *
     * @param pageNum
     * @param pageSize
     * @param criteria1
     * @param criteria2
     * @param field1
     * @param field2
     * @param sort
     * @param collectionName
     * @return
     * @throws BbsException
     */
    @Override
    public AggregationResults<T> aggregation(int pageNum, int pageSize, Criteria criteria1, Criteria criteria2,String field1, String field2, String sortName, Sort sort, String collectionName) throws BbsException {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria1),
                Aggregation.match(criteria2),
                Aggregation.group(field1, field2).last(sortName).as(sortName),
                Aggregation.sort(sort),
                Aggregation.skip((pageNum - 1) * pageSize),
                Aggregation.limit(pageSize)
        );
        return mongoTemplate.aggregate(aggregation, collectionName, clazz);
    }

    /**
     * 带条件分页排序查询,不带特殊查询条件
     *
     * @param pageNum
     * @param pageSize
     * @param condition
     * @param sort
     * @param excludeFields
     * @return
     * @throws BbsException
     */
    @Override
    public List<T> pageList(int pageNum, int pageSize, Map<String, Object> condition, Sort sort, List<String> excludeFields) throws BbsException {
        return this.pageList(pageNum, pageSize, condition, sort, excludeFields, null);
    }

    /**
     * 带条件分页排序查询,排除字段
     *
     * @param pageNum
     * @param pageSize
     * @param condition
     * @param sort
     * @param excludeFields
     * @return
     */
    @Override
    public List<T> pageList(int pageNum, int pageSize, Map<String, Object> condition, Sort sort, List<String> excludeFields, Criteria special) throws BbsException {
        Query query = new Query();
        try {
            if (condition != null) {
                condition.forEach((k, v) -> {
                    query.addCriteria(Criteria.where(k).is(v));
                });
            }
            if (special != null) {
                query.addCriteria(special);
            }
            if (excludeFields != null && excludeFields.size() > 0) {
                Field fields = query.fields();
                excludeFields.stream().forEach(t -> fields.exclude(t));
            }
            if (sort != null) {
                query.with(sort);
            }
            query.skip((pageNum - 1) * pageSize).limit(pageSize);
            return mongoTemplate.find(query, clazz);
        } catch (Exception e) {
            LOGGER.error(String.format("%s pageList error for MongoDB:{}", JSON.toJSONString(condition)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_QUERY_FAULT));
        }
    }

    /**
     * 带条件分页排序查询
     *
     * @param pageNum
     * @param pageSize
     * @param condition
     * @return
     */
    @Override

    public List<T> pageList(int pageNum, int pageSize, Map<String, Object> condition) throws BbsException {
        return this.pageList(pageNum, pageSize, condition, null);
    }

    /**
     * 按查询条件和特殊条件统计记录数
     *
     * @param condition
     * @param special
     * @return
     * @throws BbsException
     */
    @Override
    public Long recordTotal(Map<String, Object> condition, Criteria special) throws BbsException {
        Query query = new Query();
        try {
            if (condition != null) {
                condition.forEach((k, v) -> {
                    query.addCriteria(Criteria.where(k).is(v));
                });
            }
            if (special != null) {
                query.addCriteria(special);
            }
            return mongoTemplate.count(query, clazz);
        } catch (Exception e) {
            LOGGER.error(String.format("%s recordTotal error for MongoDB:{}", JSON.toJSONString(condition)), e);
            throw new BbsException(new RestFulVO(PostRetEnum.BBS_QUERY_FAULT));
        }
    }

    /**
     * 按查询条件统计记录数
     *
     * @param condition
     * @return
     */
    @Override
    public Long recordTotal(Map<String, Object> condition) throws BbsException {
        return this.recordTotal(condition, null);
    }

}

 

展开阅读全文

没有更多推荐了,返回首页