mybatisplus添加真正的批量新增、批量更新的实现方法
短信预约 -IT技能 免费直播动态提醒
这篇文章主要介绍mybatisplus添加真正的批量新增、批量更新的实现方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
使用mybatis-plus来进行批量新增和更新时,你会发现其实是一条条sql执行,下面进行优化。
1.添加InsertBatchMethod和UpdateBatchMethod类
import com.baomidou.mybatisplus.core.injector.AbstractMethod;import com.baomidou.mybatisplus.core.metadata.TableInfo;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.executor.keygen.NoKeyGenerator;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.SqlSource; @Slf4jpublic class InsertBatchMethod extends AbstractMethod { @Override public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) { final String sql = "<script>insert into %s %s values %s</script>"; final String fieldSql = prepareFieldSql(tableInfo); final String valueSql = prepareValuesSql(tableInfo); final String sqlResult = String.format(sql, tableInfo.getTableName(), fieldSql, valueSql); //log.debug("sqlResult----->{}", sqlResult); SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass); return this.addInsertMappedStatement(mapperClass, modelClass, "insertBatch", sqlSource, new NoKeyGenerator(), null, null); } private String prepareFieldSql(TableInfo tableInfo) { StringBuilder fieldSql = new StringBuilder(); fieldSql.append(tableInfo.getKeyColumn()).append(","); tableInfo.getFieldList().forEach(x -> fieldSql.append(x.getColumn()).append(",")); fieldSql.delete(fieldSql.length() - 1, fieldSql.length()); fieldSql.insert(0, "("); fieldSql.append(")"); return fieldSql.toString(); } private String prepareValuesSql(TableInfo tableInfo) { final StringBuilder valueSql = new StringBuilder(); valueSql.append("<foreach collection=\"list\" item=\"item\" index=\"index\" open=\"(\" separator=\"),(\" close=\")\">"); valueSql.append("#{item.").append(tableInfo.getKeyProperty()).append("},"); tableInfo.getFieldList().forEach(x -> valueSql.append("#{item.").append(x.getProperty()).append("},")); valueSql.delete(valueSql.length() - 1, valueSql.length()); valueSql.append("</foreach>"); return valueSql.toString(); }}
import com.baomidou.mybatisplus.core.injector.AbstractMethod;import com.baomidou.mybatisplus.core.metadata.TableInfo;import lombok.extern.slf4j.Slf4j;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.mapping.SqlSource; @Slf4jpublic class UpdateBatchMethod extends AbstractMethod { @Override public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) { String sql = "<script>\n<foreach collection=\"list\" item=\"item\" separator=\";\">\nupdate %s %s where %s=#{%s} %s\n</foreach>\n</script>"; String additional = tableInfo.isWithVersion() ? tableInfo.getVersionFieldInfo().getVersionOli("item", "item.") : "" + tableInfo.getLogicDeleteSql(true, true); String setSql = sqlSet(tableInfo.isWithLogicDelete(), false, tableInfo, false, "item", "item."); String sqlResult = String.format(sql, tableInfo.getTableName(), setSql, tableInfo.getKeyColumn(), "item." + tableInfo.getKeyProperty(), additional); //log.debug("sqlResult----->{}", sqlResult); SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass); // 第三个参数必须和RootMapper的自定义方法名一致 return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatch", sqlSource); } }
2.添加自定义方法SQL注入器
import com.baomidou.mybatisplus.core.injector.AbstractMethod;import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector; import java.util.List; public class CustomizedSqlInjector extends DefaultSqlInjector { @Override public List<AbstractMethod> getMethodList(Class<?> mapperClass) { List<AbstractMethod> methodList = super.getMethodList(mapperClass); methodList.add(new InsertBatchMethod()); methodList.add(new UpdateBatchMethod()); return methodList; }}
3.注入配置
@MapperScan("com.xxx.mapper")@Configurationpublic class MyBatisPlusConfig { @Bean public CustomizedSqlInjector customizedSqlInjector() { return new CustomizedSqlInjector(); }}
4.添加通用mapper
import com.baomidou.mybatisplus.core.mapper.BaseMapper;import org.apache.ibatis.annotations.Param; import java.util.List; public interface RootMapper<T> extends BaseMapper<T> { int insertBatch(@Param("list") List<T> list); int updateBatch(@Param("list") List<T> list);}
5.如何使用
@Repositorypublic interface UserInfoMapper extends RootMapper<UserInfo> {} public interface UserInfoService extends IService<UserInfo> { int saveAll(); int updateAll();} @Servicepublic class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService{ @Override public int saveAll() { List<UserInfo> list = new ArrayList<>(); for (int i = 0; i < 20; i++) { UserInfo userInfo = new UserInfo(); userInfo.setUserName("厉害" + i); userInfo.setSalt(RandomStringUtils.randomAlphabetic(6)); userInfo.setPassword(SecureUtil.sha256("123456" + userInfo.getSalt())); userInfo.setSex(0); userInfo.setAvatar(LoginServiceImpl.AVATAR); list.add(userInfo); } return baseMapper.insertBatch(list); } @Override public int updateAll() { List<UserInfo> userInfos = baseMapper.selectList(Wrappers.<UserInfo>lambdaQuery().between(BaseEntity::getId, 43, 62)); userInfos.forEach(userInfo -> { userInfo.setUserName("更新了" + IdUtil.simpleUUID()); }); return baseMapper.updateBatch(userInfos); }}
以上是“mybatisplus添加真正的批量新增、批量更新的实现方法”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341