1. 程式人生 > 其它 >mybatis-plus 3.4.3.1 進行批量 saveOrUpdate

mybatis-plus 3.4.3.1 進行批量 saveOrUpdate

  • service類通過 SqlHelper.saveOrUpdateBatch 實現通過自定義的 唯一索引 進行 批量儲存更新


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.enums.SqlMethod;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import org.apache.ibatis.binding.MapperMethod;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.redboard.modules.mi.base.entity.MesProdMiProc;
import cn.com.redboard.modules.mi.base.mapper.MesProdMiProcMapper;
import cn.com.redboard.modules.mi.base.service.IMesProdMiProcService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @Description: MI工藝流程Service
* @Author: wqc
* @Date: 2022-03-01
* @Version: V1.0
*/
@Service
public class MesProdMiProcServiceImpl extends ServiceImpl<MesProdMiProcMapper, MesProdMiProc> implements IMesProdMiProcService {

@Override
@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void sync(List<MesProdMiProc> prodMiProcList) {

// 每2000條語句,進行一次sqlSession.flushStatements()
SqlHelper.saveOrUpdateBatch(this.entityClass, this.mapperClass, this.log, prodMiProcList, 2000, (sqlSession, entity) -> {
MapperMethod.ParamMap param = new MapperMethod.ParamMap();

Object erpProcessId = ReflectionKit.getFieldValue(entity, ${otherUniqueIdx}
);
LambdaQueryWrapper<MesProdMiProc> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MesProdMiProc::getErpProcessId, erpProcessId);
// 自定義查詢條件
param.put("ew", queryWrapper);

// 判斷記錄是否存在,存在則更新,否則插入
return StringUtils.checkValNull(erpProcessId) || CollectionUtils.isEmpty(sqlSession.selectList(this.getSqlStatement(SqlMethod.SELECT_LIST), param));
}, (sqlSession, entity) -> {
MapperMethod.ParamMap param = new MapperMethod.ParamMap();
// 需要更新的當前記錄實體
param.put("et", entity);

LambdaQueryWrapper<MesProdMiProc> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(MesProdMiProc::getErpProcessId, ReflectionKit.getFieldValue(entity, ${otherUniqueIdx}
));
            // 自定義查詢條件
            param.put("ew", queryWrapper);

sqlSession.update(this.getSqlStatement(SqlMethod.UPDATE), param);
});

}

}

 

  • SqlHelper.saveOrUpdateBatch具體原始碼

 

 


  • SqlHelper.executeBatch具體原始碼