1. 程式人生 > >SpringBoot 整合MongoDB的基本操作

SpringBoot 整合MongoDB的基本操作

話不多說,直接上程式碼(轉載務必說明出處  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);
    }

}