mongodb 批量更新3.0版本后

网上大部分是过时的博客,自己研究了一下午。新版的用法。代码如下

package com.fuli.goods.mongo;

import com.fuli.goods.entity.mgdb.ComGoodsCacheEntity;
import com.fuli.goods.utils.ComUtils;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.BulkOperations;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CompanyGoodsCacheDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     *
     * @param comGoodsCacheEntity
     */
    public void savecomGoodsCacheEntity(ComGoodsCacheEntity comGoodsCacheEntity) {
        mongoTemplate.save(comGoodsCacheEntity);
        mongoTemplate.getDb();

    }

    public ComGoodsCacheEntity findById(String id) {
        return mongoTemplate.findById(id,ComGoodsCacheEntity.class);
    }
    /**
     * 根据用户名查询对象
     *
     * @param
     * @return
     */
    public List<ComGoodsCacheEntity> findByParam(ComGoodsCacheEntity  comGoodsCacheEntity) {
        Query query = new Query();
        if(comGoodsCacheEntity.getGoodsId()!=null&&comGoodsCacheEntity.getGoodsId().intValue()!=0){
            query.addCriteria(Criteria.where("goodsId").is(comGoodsCacheEntity.getGoodsId()));
        }
        if(comGoodsCacheEntity.getCompanyId()!=null&&comGoodsCacheEntity.getCompanyId().intValue()!=0){
            query.addCriteria(Criteria.where("companyId").is(comGoodsCacheEntity.getCompanyId()));
        }
        if(comGoodsCacheEntity.getIsShow()!=null){
            query.addCriteria(Criteria.where("isShow").is(comGoodsCacheEntity.getIsShow()));
        }
        if(comGoodsCacheEntity.getTypeId()!=null&&comGoodsCacheEntity.getTypeId().intValue()!=0){
            query.addCriteria(Criteria.where("typeId").is(comGoodsCacheEntity.getTypeId()));
        }
        if(comGoodsCacheEntity.getMaxSalePrice()!=null&&comGoodsCacheEntity.getMinSalePrice().compareTo(BigDecimal.ZERO)!=0){
            query.addCriteria(Criteria.where("goodsSalePrice").lt(comGoodsCacheEntity.getMaxSalePrice()));
        }
        if(comGoodsCacheEntity.getMinSalePrice()!=null&&comGoodsCacheEntity.getMinSalePrice().compareTo(BigDecimal.ZERO)!=0){
            query.addCriteria(Criteria.where("goodsSalePrice").is(comGoodsCacheEntity.getMinSalePrice()));
        }
        List<ComGoodsCacheEntity> list = mongoTemplate.find(query, ComGoodsCacheEntity.class);
        return list;
    }

    /**
     * 更新对象
     *
     * @param comGoodsCacheEntity
     */
    public long updatecomGoodsCacheEntity(ComGoodsCacheEntity comGoodsCacheEntity) {
        Query query = new Query(Criteria.where("companyId").is(comGoodsCacheEntity.getCompanyId()).andOperator(Criteria.where("goodsId").is(comGoodsCacheEntity.getGoodsId())));
        Update update = new Update().set("goodsPrice", comGoodsCacheEntity.getGoodsPrice())
                .set("goodsSalePrice", comGoodsCacheEntity.getGoodsSalePrice())
                .set("goodsMarketPrice", comGoodsCacheEntity.getGoodsMarketPrice())
                .set("IntegralPrice", comGoodsCacheEntity.getIntegralPrice())
                .set("isShow", comGoodsCacheEntity.getIsShow())
                .set("profitRate", comGoodsCacheEntity.getProfitRate())
                .set("sort", comGoodsCacheEntity.getSort())
                .set("goodsName",comGoodsCacheEntity.getGoodsName())
                .set("typeId", comGoodsCacheEntity.getTypeId());

        //更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, ComGoodsCacheEntity.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,comGoodsCacheEntityEntity.class);
        if(result != null) return result.getModifiedCount();
        else return 0;
    }

    /**
     * 删除对象
     *
     * @param id
     */
    public void deletecomGoodsCacheEntityById(Long id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query, ComGoodsCacheEntity.class);
    }


    /**
     * 批量更新
     *
     * @param
     * @return
     */
    public int bathUpdate(List<ComGoodsCacheEntity> lists) {

        List<ComGoodsCacheEntity> tlist=new ArrayList<>();
        for(int i=0;i<lists.size();i++){
            tlist.add(lists.get(i));
            if(tlist!=null&&tlist.size()>10000){
                try {
                    doUpdate(tlist);

                }catch (Exception e){
                    e.printStackTrace();
                    log.error("批量更新公司商品错误!{}",e.getMessage());
                }
                tlist=new ArrayList<>();
            }
        }
        if(tlist!=null&&tlist.size()>0){
            doUpdate(tlist);
        }
        return 1;
    }


    /**
     * 批量插入
     *
     * @param
     * @return
     */
    public int bathInsert(List<ComGoodsCacheEntity> comGoodsCacheEntitys) {
        List<ComGoodsCacheEntity> tlist=new ArrayList<>();
        for(ComGoodsCacheEntity cacheEntity:comGoodsCacheEntitys){
            tlist.add(cacheEntity);
            if(tlist.size()>=10000){
                mongoTemplate.insertAll(tlist);
                tlist=new ArrayList<>();
            }
        }
        if(tlist!=null && tlist.size()>0){
            mongoTemplate.insertAll(tlist);
        }
        return 1;
    }

    public void doUpdate(List<ComGoodsCacheEntity> cacheEntities){
        String collectionName= ComUtils.determineCollectionName(ComGoodsCacheEntity.class);
        BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, Object.class, collectionName);
        cacheEntities.parallelStream().forEach(comGoods -> {
            Criteria criteria=Criteria.where("companyId").is(comGoods.getCompanyId()).and("goodsId").is(comGoods.getGoodsId());
            Update update = new Update();
            //更新内容
            update.set("goodsName",comGoods.getGoodsName());
            update.set("goodsPrice", comGoods.getGoodsPrice());
            update.set("goodsSalePrice", comGoods.getGoodsSalePrice());
            update.set("goodsMarketPrice", comGoods.getGoodsMarketPrice());
            update.set("IntegralPrice", comGoods.getIntegralPrice());
            update.set("isShow", comGoods.getIsShow());
            update.set("profitRate", comGoods.getProfitRate());
            update.set("sort", comGoods.getSort());
            update.set("typeId", comGoods.getTypeId());
            bulkOps.updateOne(Query.query(criteria), update);
        });
        bulkOps.execute();
    }
}
public class ComUtils {

    public static String determineCollectionName(Class<?> entityClass) {
        if (entityClass == null) {
            throw new InvalidDataAccessApiUsageException(
                    "No class parameter provided, entity collection can't be determined!");
        }
        String collName = entityClass.getSimpleName();
        if(entityClass.isAnnotationPresent(Document.class)) {
            Document document = entityClass.getAnnotation(Document.class);
            collName = document.collection();
        } else {
            collName = collName.replaceFirst(collName.substring(0, 1)
                    ,collName.substring(0, 1).toLowerCase()) ;
        }
        return collName;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_18630487/article/details/88802727