mybatis-plus 自带的saveOrUpdateBatch 是以主键来判断插入 或更新的, 如何根据唯一索引实现呢?
## mysql 定义唯一索引 unique key: (salary_date, tenant_id, type, id_no)
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveOrUpdateBatchByUniqueKey(List<Salary> list) {
// 这里主要是查询唯一约束对应的记录是否存在
return SqlHelper.saveOrUpdateBatch(entityClass, this.mapperClass, super.log, list, DEFAULT_BATCH_SIZE, (sqlSession, entity) -> {
LambdaQueryWrapper<Salary> queryWrapper = Wrappers.<Salary>lambdaQuery()
.eq(Salary::getSalaryDate, entity.getSalaryDate())
.eq(Salary::getTenantId, entity.getTenantId())
.eq(Salary::getType, entity.getType())
.eq(Salary::getIdNo, entity.getIdNo());
Map<String, Object> queryParam = CollectionUtils.newHashMapWithExpectedSize(1);
queryParam.put(com.baomidou.mybatisplus.core.toolkit.Constants.WRAPPER, queryWrapper);
return CollectionUtils.isEmpty(sqlSession.selectList(getSqlStatement(SqlMethod.SELECT_LIST), queryParam));
}, (sqlSession, entity) -> {
LambdaUpdateWrapper<Salary> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(Salary::getSalaryDate, entity.getSalaryDate())
.eq(Salary::getTenantId, entity.getTenantId())
.eq(Salary::getType, entity.getType())
.eq(Salary::getIdNo, entity.getIdNo());
Map<String, Object> param = CollectionUtils.newHashMapWithExpectedSize(2);
param.put(com.baomidou.mybatisplus.core.toolkit.Constants.ENTITY, entity);
param.put(com.baomidou.mybatisplus.core.toolkit.Constants.WRAPPER, updateWrapper);
sqlSession.update(getSqlStatement(SqlMethod.UPDATE), param);
});
}