Java如何优雅的处理插入数据,数据库有相同的数据则更新,没有的话则插入

一、前言

相信小伙伴们在做后台开发的时候,经常要用到CRUD。经常用CRUD并不丢人,关键是怎么把CRUD用到更简洁、更极致,这样的一直下去的话,其实你慢慢的也成为了你眼中的那些大神们。我这里是用到了 JDK1.8的一些特性,不了解 JDK1.8的新特性的话,可以先简单了解一下。

好了,废话不多说,我直接上代码了。

二、代码实现

package com.riemann.springbootdemo.service.impl;

import com.google.common.collect.Maps;
import com.riemann.springbootdemo.dao.PoiShopDao;
import com.riemann.springbootdemo.model.PoiShopEntity;
import com.riemann.springbootdemo.service.PoiShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author riemann
 * @date 2020/02/14 21:00
 */
public class PoiShopServiceImpl implements PoiShopService {

    @Autowired
    private PoiShopDao poiShopDao;

    @Override
    public Integer updataOrInsert(List<PoiShopEntity> shopList) {
        int amount = 0;
        Map<String, List> dataMap = validateShopData(shopList);
        for (String key : dataMap.keySet()) {
            if ("insert".endsWith(key)) {
                amount = poiShopDao.uploadShopData(dataMap.get(key));
            } else {
                amount = poiShopDao.updateBatchShopData(dataMap.get(key));
            }
        }
        return amount;
    }

    private Map<String, List> validateShopData(List<PoiShopEntity> shopEntityList) {
        HashMap<String, List> result = Maps.newHashMap();
        List<PoiShopEntity> shopList = poiShopDao.selectSelectiveList(shopEntityList);
        // 取差集
        List<PoiShopEntity> shopInsertList = shopList.stream().
                filter(item -> findShopData(item.getPoiId(), item.getSource(), shopList) == -1)
                .collect(Collectors.toList());
        // 取并集
        List<PoiShopEntity> shopUpdataList = shopList.stream().
                filter(item -> findShopData(item.getPoiId(), item.getSource(), shopList) > -1)
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(shopInsertList)) {
            result.put("insert", shopInsertList);
        } else {
            result.put("update", shopUpdataList);
        }
        return result;
    }

    private int findShopData(String poiId, Integer source, List<PoiShopEntity> shopList) {
        int res = -1;
        for (int i = 0; i < shopList.size(); i++) {
            if (poiId.equals(shopList.get(i).getPoiId()) && source.intValue() == shopList.get(i).getSource()) {
                res = i;
                break;
            }
        }
        return res;
    }
}

是不是看着比较简洁一些了?如果你又更好的方式实现,可以留言分享一下。

发布了386 篇原创文章 · 获赞 313 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/riemann_/article/details/104320812