Java基于MongoDB Template封装Dao层

mongoDB Template 提供了许多直接操作Mongo的方法, 在此基础上在进行一层封装, 用起来更顺手

1.Dao层的抽象类, 封装了常用的几个方法
tips: 对实体有要求, 属性不同, 一些私有方法请自行修改

/**
 * @author Lynn
 * @version 2022/08/15
 */
@SuppressWarnings(value = {"unchecked"})
public abstract class AbstractMongoDaoImpl<T extends BaseFeedEntity> {

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 分页查询
     *
     * @param entity {@link T}
     * @return {@link PageInfo}
     */
    public PageInfo<T> queryPage(T entity) {
        Query query = this.buildQueryCriteria(entity);
        long total = mongoTemplate.count(query, entity.getClass());
        if (total == 0) {
            return PageInfo.of(Lists.newArrayList());
        }
        List<T> pageList = (List<T>) mongoTemplate.find(query.limit(entity.getPageSize()).skip((entity.getPageNum() - 1) * entity.getPageSize()), entity.getClass());
        PageInfo<T> pageInfo = PageInfo.of(pageList);
        pageInfo.setTotal(total);
        pageInfo.setPageNum(entity.getPageNum());
        pageInfo.setPageSize(entity.getPageSize());
        pageInfo.setPages((int) (total / entity.getPageSize() + (total % entity.getPageSize() != 0 ? 1 : 0)));
        return pageInfo;
    }

    /**
     * 列表查询
     *
     * @param entity {@link T}
     * @return {@link List}
     */
    public List<T> queryList(T entity) {
        return (List<T>) mongoTemplate.find(this.buildQueryCriteria(entity), entity.getClass());
    }

    /**
     * 查询记录条数
     *
     * @param entity {@link T}
     * @return 记录条数
     */
    public long count(T entity) {
        return mongoTemplate.count(this.buildQueryCriteria(entity), entity.getClass());
    }

    /**
     * 详情查询
     *
     * @param entity {@link T}
     * @return {@link T}
     */
    public T findOne(T entity) {
        return (T) mongoTemplate.findOne(this.buildQueryCriteria(entity), entity.getClass());
    }

    /**
     * 根据主键查询详情
     *
     * @param entity {@link T}
     * @return {@link T}
     */
    public T findById(T entity) {
        return (T) mongoTemplate.findById(entity.getId(), entity.getClass());
    }

    /**
     * 新增
     *
     * @param entity {@link T}
     * @return ObjectId
     */
    public String insert(T entity) {
        this.handleInsertInfo(entity);
        T ins = mongoTemplate.insert(entity);
        return ins.getId();
    }

    /**
     * 根据主键更新
     *
     * @param entity {@link T}
     * @return {@link Boolean}
     */
    public boolean save(T entity) {
        T originEntity = findById(entity);
        if (null != originEntity) {
            BeanUtil.copyProperties(entity, originEntity, CopyOptions.create().setIgnoreNullValue(true));
            this.handleUpdateInfo(originEntity);
            mongoTemplate.save(originEntity);
            return true;
        }
        return false;
    }

    /**
     * 根据主键删除
     *
     * @param entity {@link T}
     * @return {@link Boolean}
     */
    public boolean deleteById(T entity) {
        T originEntity = findById(entity);
        if (null != originEntity) {
            this.handleDeleteInfo(originEntity);
            mongoTemplate.save(originEntity);
            return true;
        }
        return false;
    }

    /**
     * 组装查询条件
     *
     * @param entity {@link T}
     * @return {@link Query}
     */
    abstract Query buildQueryCriteria(T entity);

    /**
     * 组装更新基础参数
     *
     * @param entity {@link T}
     */
    private void handleUpdateInfo(T entity) {
        if (Objects.isNull(entity)) {
            return;
        }
        entity.setUpdateTime(new Date());
        entity.setUpdateBy(IAuthService.getUserId());
    }

    /**
     * 组装新增基础参数
     *
     * @param entity {@link T}
     */
    private void handleInsertInfo(T entity) {
        this.handleUpdateInfo(entity);
        entity.setCreateTime(new Date());
        entity.setCreatedBy(IAuthService.getUserId());
    }

    /**
     * 组装删除基础参数
     *
     * @param entity {@link T}
     */
    private void handleDeleteInfo(T entity) {
        this.handleUpdateInfo(entity);
        entity.setDelFlag(true);
    }
}
  1. 通用Dao层接口
    和抽象类里暴露的方法是对应的
/**
 * @author Lynn
 * @date 2022/08/15
 */
public interface CommonMongoDao<T> {

    /**
     * 分页查询
     *
     * @param entity {@link T}
     * @return {@link PageInfo }
     */
    PageInfo<T> queryPage(T entity);

    /**
     * 列表查询
     *
     * @param entity {@link T}
     * @return {@link List}
     */
    List<T> queryList(T entity);

    /**
     * 查询记录条数
     *
     * @param entity {@link T}
     * @return 记录条数
     */
    long count(T entity);

    /**
     * 详情查询
     *
     * @param entity {@link T}
     * @return {@link T}
     */
    T findOne(T entity);

    /**
     * 根据主键查询详情
     *
     * @param entity {@link T}
     * @return {@link T}
     */
    T findById(T entity);

    /**
     * 新增
     *
     * @param entity {@link T}
     * @return ObjectId
     */
    String insert(T entity);

    /**
     * 根据主键更新
     *
     * @param entity {@link T}
     * @return {@link Boolean}
     */
    boolean save(T entity);

    /**
     * 根据主键删除
     *
     * @param entity {@link T}
     * @return {@link Boolean}
     */
    boolean deleteById(T entity);
}
  1. 子类Dao层接口
    子类Dao层接口继承通用Dao层接口, 内部只需写自己独有的方法即可
/**
 * @author Lynn
 * @date 2022/08/15
 */
interface ReserveOrderDao extends CommonMongoDao<ReserveOrderEntity> {

    /**
     * 统计免费单数量
     *
     * @param entity {@link ReserveOrderEntity}
     * @return {@link Long}
     */
    long countFreeOrders(ReserveOrderEntity entity);
}
  1. 子类Dao层实现
    子类Dao层实现只需要实现独有的方法, 以及实现抽象类中抽象方法即可
/**
 * @author Lynn
 * @version 2022/08/15
 */
@Repository("reserveOrderDao")
public class ReserveOrderDaoImpl extends AbstractMongoDaoImpl<ReserveOrderEntity> implements ReserveOrderDao {

    @Override
    public long countFreeOrders(ReserveOrderEntity entity) {
        return super.mongoTemplate.count(this.buildCountFreeOrderCriteria(entity), ReserveOrderEntity.class);
    }

    @Override
    public Query buildQueryCriteria(ReserveOrderEntity entity) {
        Criteria criteria = new Criteria();
        criteria.and("delFlag").is(false);

        if (StringUtils.isNotBlank(entity.getFeedId())) {
            criteria.and("feedInfos.feedId").is(entity.getFeedId());
        }
        if (StringUtils.isNotBlank(entity.getIdentityNo())) {
            criteria.and("reserveCustomer.idNo").is(entity.getIdentityNo());
        }
        if (StringUtils.isNotBlank(entity.getTenantId())) {
            criteria.and("tenantId").is(entity.getTenantId());
        }
        if (StringUtils.isNotBlank(entity.getOrgId())) {
            criteria.and("orgId").is(entity.getOrgId());
        }
        if (StringUtils.isBlank(entity.getOrgId()) && CollectionUtils.isNotEmpty(entity.getOrgIds())) {
            criteria.and("orgId").in(entity.getOrgIds());
        }
        if (entity.getServeTimeMin() != null) {
            criteria.and("serveTime").gte(entity.getServeTimeMin());
        }
        if (entity.getServeTimeMax() != null) {
            criteria.and("serveTime").lte(entity.getServeTimeMax());
        }
        Query query = new Query(criteria);
        query.with(Sort.by(Sort.Direction.DESC, "createTime"));
        return query;
    }

    private Query buildCountFreeOrderCriteria(ReserveOrderEntity entity) {
        Criteria criteria = new Criteria();
        criteria.and("delFlag").is(false);

        if (StringUtils.isNotBlank(entity.getFeedId())) {
            criteria.and("feedInfos.feedId").is(entity.getFeedId());
        }
        if (StringUtils.isNotBlank(entity.getIdentityNo())) {
            criteria.and("reserveCustomer.idNo").is(entity.getIdentityNo());
        }
        criteria.and("status").ne(OrderStatusEnum.CANCEL.getState());
        criteria.and("freeOrder").is(true);
        if (entity.getStartTime() != null && entity.getEndTime() != null) {
            criteria.and("createTime").gte(entity.getStartTime()).lte(entity.getEndTime());
        }
        if (StringUtils.isNotBlank(entity.getTenantId())) {
            criteria.and("tenantId").is(entity.getTenantId());
        }
        if (StringUtils.isNotBlank(entity.getOrgId())) {
            criteria.and("orgId").is(entity.getOrgId());
        }
        return new Query(criteria);
    }
}

你可能感兴趣的:(MongoDB,mongodb,java,数据库)