欢迎大家关注我的公众号【老周聊架构】,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;
}
}
是不是看着比较简洁一些了?如果你又更好的方式实现,可以留言分享一下。