唯一索引注解
package com.zk.fahai.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FhId {}
拓展服务类,使用时extend即可
package com.zk.fahai.util;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zk.fahai.common.annotation.FhId;
import com.zk.fx.common.util.JsonUtils;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
@Transactional(rollbackFor = Exception.class)
public void saveOrUpdateBatchByFhId(Collection entityList) throws IOException {
TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
Assert.notNull(
tableInfo, "error: can not execute. because can not find cache of TableInfo for entity!");
List ukFieldNameList =
tableInfo.getFieldList().stream()
.filter(c -> c.getField().isAnnotationPresent(FhId.class))
.map(tableFieldInfo -> tableFieldInfo.getField().getName())
.collect(Collectors.toList());
if (ukFieldNameList.size() < 1) {
logger.error("未找到唯一索引,class:{}", tableInfo.getEntityType());
return;
}
for (List list : this.cutList(entityList, IService.DEFAULT_BATCH_SIZE)) {
try {
super.saveBatch(list);
} catch (DuplicateKeyException duplicateKeyException) {
for (T entity : list) {
try {
super.save(entity);
} catch (DuplicateKeyException e2) {
logger.info("数据更新触发唯一索引,对象:{}", JsonUtils.object2JsonString(entity));
UpdateWrapper updateWrapper = new UpdateWrapper<>();
ukFieldNameList.forEach(
uk -> updateWrapper.eq(uk, ReflectionKit.getFieldValue(entity, uk)));
super.update(entity, updateWrapper);
}
}
}
}
}
public List> cutList(Collection list, int maxNum) {
int step = (list.size() + maxNum - 1) / maxNum;
return Stream.iterate(0, n -> n + 1)
.limit(step)
.parallel()
.map(
a ->
list.stream()
.skip(a * maxNum)
.limit(maxNum)
.parallel()
.collect(Collectors.toList()))
.collect(Collectors.toList());
}
}