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 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 shopEntityList) {

HashMap<String, List> result = Maps.newHashMap();

List shopList = poiShopDao.selectSelectiveList(shopEntityList);

// 取差集

List shopInsertList = shopList.stream().

filter(item -> findShopData(item.getPoiId(), item.getSource(), shopList) == -1)

.collect(Collectors.toList());

// 取并集

List shopUpdataList = shopList.stream().

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,如果想要找出一个数组中的重复数据,我们可以考虑使用HashSet(哈希集合)来实现。HashSet是一种基于哈希算法实现的集合,它通过将元素的存储与计算分离来实现高效的查找和插入。 具体步骤如下: 1. 创建一个HashSet对象,并将数组中的所有数据添加到HashSet中。 2. 创建一个空的ArrayList对象,用于存放重复的数据。 3. 遍历数组中的每一个元素,如果当前元素已经存在于HashSet中,则说明这个元素是重复的,将它添加到ArrayList中。 4. 遍历结束后,ArrayList中存放的就是所有重复的数据。 下面是具体实现的示例代码: ```java import java.util.ArrayList; import java.util.HashSet; public class Test { public static void main(String[] args) { // 定义一个数组,包含重复数据 int[] arr = {1, 2, 3, 3, 4, 5, 5, 6}; // 创建HashSet对象,并将数组中所有数据添加到HashSet中 HashSet<Integer> set = new HashSet<Integer>(); for (int i = 0; i < arr.length; i++) { set.add(arr[i]); } // 创建ArrayList对象,用于存放重复的数据 ArrayList<Integer> list = new ArrayList<Integer>(); // 遍历数组中的每一个元素 for (int i = 0; i < arr.length; i++) { // 如果当前元素已经存在于HashSet中,则说明这个元素是重复的 if (!set.add(arr[i])) { // 将它添加到ArrayList中 list.add(arr[i]); } } // 输出结果 System.out.println("重复的数据为:" + list); } } ``` 运行上面的代码,将会输出以下结果: > 重复的数据为:[3, 5]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值