springboot整合mongdb

在业务中我们整合了mongoDB,以下是我们mongoDB的Dao层增删查改的相关实现。

环境依赖

1、首先我们需要在pom中添加mongoDB对应的依赖


   org.springframework.boot
   spring-boot-starter-data-mongodb

数据源配置

2、我们需要在配置文件中添加mongoDB的数据源配置

spring:
  data:
    mongodb:
      uri: mongodb://zhd:[email protected]:27017/test

注意:zhd是账户名,123456是指账户密码,test是指数据库名

实体类

3、这里我们创建一个用户的实体类

package com.yangcuncloud.consumer.model;

import com.yangcuncloud.consumer.annotation.AutoIncKey;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.Serializable;
import java.util.*;

@Document(collection = "consumer")
public class Consumer implements Serializable {


    private static final long serialVersionUID = -4708301308819659797L;
    @AutoIncKey
    @Id
    private long id=0L;        //id
    private int status;        //状态
    private String consumerName;        //会员名(不可改)
    private String consumerRealName;        //真实姓名
    private String consumerNickName;        //昵称
    private String consumerPhone;        //绑定电话
    private String consumerLevel;        //会员级别
    private String unionid;        //unionid
    private String consumerNo;        //会员编号
    private String headimgurl;        //头像
    private String province;        //省
    private String city;        //市
    private String area;        //区
    private String addr;        //详细地址

    private Date ctime;         //创建时间
    private Date mtime;         //修改时间

    private List baby;        //宝宝集合
    private List wxUser;        //微信集合
    private List
addresses; //会员地址集合 private List roles; //get和set和构造方法略 }

数据操作Dao层接口

4、创建Dao的接口

package com.yangcuncloud.consumer.dao;

import com.alibaba.fastjson.JSONObject;
import com.yangcuncloud.consumer.model.Consumer;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

public interface ConsumerDao {

    void removeConsumer(Long id);//删除

    void saveConsumer(Consumer consumer);//保存

    void updateConsumer(Long id, JSONObject paramJson);//更新

    void updateConsumerTag(Query query,Update update);//修改子节点

    void updateConsumerAddTag(Query query,Update update);//添加子节点

    Consumer queryConsumerBYyId(Long consumerId);//主键查询

    Consumer queryConsumerByPhone(String phone);//条件查询

    Page queryConsumerList(int page, int pageSize, Sort sort, Query query);//分页查询
}


4、创建Dao的实现

package com.yangcuncloud.consumer.dao;

import com.alibaba.fastjson.JSONObject;
import com.yangcuncloud.consumer.model.Consumer;
import com.yangcuncloud.consumer.util.SpringDataPageable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
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.stereotype.Component;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

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

@Component
public class ConsumerDaoImpl implements ConsumerDao {

//引入MongoTemplate
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void removeConsumer(Long id) {
        Query query =new Query();
        query.addCriteria(Criteria.where("id").is(id));
        mongoTemplate.remove(query,Consumer.class);

    }

    @Override
    public void saveConsumer(Consumer consumer) {
        mongoTemplate.save(consumer);
    }
//更新逻辑为,先查询出需要更新的内容,然后再将内容修改
//此处为整体修改 paramJson参数为需要修改的内容K-V
    @Override
    public void updateConsumer(Long id, JSONObject paramJson) {
        Query query =new Query();
        query.addCriteria(Criteria.where("id").is(id));
        Update update=new Update();
        for (Map.Entry entry : paramJson.entrySet()) {
            update.set(entry.getKey(),entry.getValue());
        }
        mongoTemplate.updateFirst(query,update,Consumer.class);

    }

//此处为修改数据的内部节点,在service的实现中有更详细的处理
    @Override
    public void updateConsumerTag(Query query, Update update) {

        mongoTemplate.updateMulti(query,update,Consumer.class);

    }
//此处为在数据的内部节点添加数据,在service的实现中有更详细的处理
    @Override
    public void updateConsumerAddTag(Query query, Update update) {
        mongoTemplate.upsert(query,update,Consumer.class);
    }

//主键查询
    @Override
    public Consumer queryConsumerBYyId(Long consumerId) {
        Query query = new Query(Criteria.where("id").is(consumerId));
        return mongoTemplate.findOne(query, Consumer.class);
    }

//根据电话查询,一个基本的例子,实际中可以是任何条件
    @Override
    public Consumer queryConsumerByPhone(String phone) {
        Query query = new Query(Criteria.where("consumerPhone").is(phone));
        return mongoTemplate.findOne(query, Consumer.class);
    }
//分页查询
    @Override
    public Page queryConsumerList(int page, int pageSize, Sort sort, Query query) {

        if (null == sort) {

            List orders = new ArrayList();
            orders.add(new Order(Sort.Direction.DESC, "id"));
            sort = new Sort(orders);
        }
        query.with(sort);
        SpringDataPageable pageable = new SpringDataPageable();
        //开始页
        pageable.setPagenumber(page);
        //每页条数
        pageable.setPagesize(pageSize);
        //排序
        pageable.setSort(sort);
        //查询出一共的条数
        Long count = mongoTemplate.count(query, Consumer.class);
        //查询
        List list = mongoTemplate.find(query.with(pageable), Consumer.class);
        //将集合与分页结果封装
        Page pagelist = new PageImpl(list, pageable, count);
        return pagelist;
    }


}

业务操作service层

5、此处省略service接口,一下是service的实现

package com.yangcuncloud.consumer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yangcuncloud.consumer.dao.ConsumerDao;
import com.yangcuncloud.consumer.model.Address;
import com.yangcuncloud.consumer.model.Consumer;
import com.yangcuncloud.consumer.service.ConsumerService;
import com.yangcuncloud.consumer.util.ResponseEntity;
import com.yangcuncloud.consumer.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
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 java.util.List;
import java.util.Map;

@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private ConsumerDao consumerDaoImpl;

    /**
     * 新建会员(使用自增id)
     *
     * @param consumer
     * @return
     */
    @Override
    public Consumer saveConsumer(Consumer consumer) {
        consumerDaoImpl.saveConsumer(consumer);
        return consumer;
    }

    /**
     * 根据id查询会员
     *
     * @param consumerId
     * @return
     */
    @Override
    public Consumer queryConsumerById(Long consumerId) {
        return consumerDaoImpl.queryConsumerBYyId(consumerId);
    }

    /**
     * 根据手机号查询会员
     *
     * @param consumerPhone
     * @return
     */
    @Override
    public Consumer queryConsumerByPhone(String consumerPhone) {

        return consumerDaoImpl.queryConsumerByPhone(consumerPhone);
    }

    /**
     * 无条件分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public JSONObject queryConsumerList(int page, int pageSize, Sort sort) {
        Page consumers = consumerDaoImpl.queryConsumerList(page, pageSize, sort, new Query());
        JSONObject outJsonObject = new JSONObject();
        outJsonObject.put("list", consumers.getContent());
        outJsonObject.put("totalCount", consumers.getTotalElements());
        outJsonObject.put("totalPages", consumers.getTotalPages());
        return outJsonObject;
    }

    /**
     * 模糊分页查询
     *
     * @param page
     * @param pageSize
     * @param sort
     * @param param
     * @return
     */
    @Override
    public JSONObject queryConsumerList(int page, int pageSize, Sort sort, JSONObject param) {
        Query query = new Query();
        Criteria criteria = new Criteria();
        for (Map.Entry entry : param.entrySet()) {
            query.addCriteria(criteria.and(entry.getKey()).regex(".*?" + entry.getValue() + ".*"));
        }
        Page consumers = consumerDaoImpl.queryConsumerList(page, pageSize, sort, query);
        JSONObject outJsonObject = new JSONObject();
        outJsonObject.put("list", consumers.getContent());
        outJsonObject.put("totalCount", consumers.getTotalElements());
        outJsonObject.put("totalPages", consumers.getTotalPages());
        return outJsonObject;
    }
 /**
     * 添加地址【这是一个典型的添加数据内部节点的数据】
     */
    @Override
    public int addUserAddress(Long consumerId, Address address) {
        //新增地址id赋值 UUID
        address.setAddressId(UUIDUtils.random());
        Consumer consumer = this.queryConsumerById(consumerId);
        if (consumer != null) {
            //若新增为默认地址将原地址集合中默认地址清掉
            if (address.getIsDefault() == 1) {
                this.removeAddressesDefault(consumerId);
            }
            Query query = Query.query(Criteria.where("id").is(consumerId));
            Update update = new Update();
            update.addToSet("addresses", address);
            consumerDaoImpl.updateConsumerAddTag(query, update);
            return 0;
        }
        return 1801152109;
    }
 /**
     * 设置默认地址
     */
    @Override
    public int setUserDefaultAddress(Long consumerId, String addressId) {
        Consumer consumer = this.queryConsumerById(consumerId);
        if (consumer == null) {
            return 1801152112;
        }
        //将原地址集合中默认地址清掉
        this.removeAddressesDefault(consumerId);

        //设为默认地址
        Query query = Query.query(Criteria.where("id").is(consumerId)
                .and("addresses.addressId").is(addressId));
        Update update = new Update();
        update.set("addresses.$.isDefault", 1);
        consumerDaoImpl.updateConsumerTag(query, update);
        return 0;
    }
 /**
     * 求改默认地址状态【这是一个典型的修改数据内部节点】
     */
    @Override
    public void removeAddressesDefault(Long consumerId) {
        Query query = Query.query(Criteria.where("id").is(consumerId)
                .and("addresses.isDefault").is(1));
        Update update = new Update();
        update.set("addresses.$.isDefault", 0);
        consumerDaoImpl.updateConsumerTag(query, update);
    }
}

mongodb的分组统计排序。

  以下是业务逻辑:

操作日志类

private String userId;                            //用户id
private String articleId;                         //文章id
private Long time;                              //时间
private int type;         						//操作类型

任何一个用户点击进入任何一篇文章都会记录一条type为9的操作日志,

现在需要统计:1个月内文章的阅读量排序


也就是:将时间段内同时类型为9的操作日志,按照articleId【文章id】字段分组,按每一组的总行数倒序输出。

以下是业务实现

@Override
public List getReadCount() {
    Long startTime = new Date().getTime() - (60 * 1000 * 60 * 24 * 30L);
    Long endTime = new Date().getTime();
    Aggregation agg = null;
    List orders = new ArrayList();
    orders.add(new Sort.Order(Sort.Direction.DESC, "count"));
    Sort sort = new Sort(orders);
    Criteria criteria = Criteria.where("type").is(9).and("time").gte(startTime).lte(endTime);//条件
    GroupOperation groupOperation = Aggregation.group("articleId").count().as("count");//按照articleId分组,以行数为统计
    agg = Aggregation.newAggregation(OperationLog.class, Aggregation.match(criteria), groupOperation, Aggregation.sort(sort));//参数:查询class,条件,分组,排序
    return mongoTemplate.aggregate(agg, OperationLog.class, SortCount.class).getMappedResults();
}


 
 

你可能感兴趣的:(springcloud)