您好,登錄后才能下訂單哦!
這篇文章主要介紹mybatisplus添加真正的批量新增、批量更新的實(shí)現(xiàn)方法,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
使用mybatis-plus來(lái)進(jìn)行批量新增和更新時(shí),你會(huì)發(fā)現(xiàn)其實(shí)是一條條sql執(zhí)行,下面進(jìn)行優(yōu)化。
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; /** * 批量插入方法實(shí)現(xiàn) */ @Slf4j public 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; /** * 批量更新方法實(shí)現(xiàn),條件為主鍵,選擇性更新 */ @Slf4j public 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); // 第三個(gè)參數(shù)必須和RootMapper的自定義方法名一致 return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatch", sqlSource); } }
import com.baomidou.mybatisplus.core.injector.AbstractMethod; import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector; import java.util.List; public class CustomizedSqlInjector extends DefaultSqlInjector { /** * 如果只需增加方法,保留mybatis plus自帶方法, * 可以先獲取super.getMethodList(),再添加add */ @Override public List<AbstractMethod> getMethodList(Class<?> mapperClass) { List<AbstractMethod> methodList = super.getMethodList(mapperClass); methodList.add(new InsertBatchMethod()); methodList.add(new UpdateBatchMethod()); return methodList; } }
@MapperScan("com.xxx.mapper") @Configuration public class MyBatisPlusConfig { @Bean public CustomizedSqlInjector customizedSqlInjector() { return new CustomizedSqlInjector(); } }
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 根Mapper,給表Mapper繼承用的,可以自定義通用方法 * {@link com.baomidou.mybatisplus.core.mapper.BaseMapper} * {@link com.baomidou.mybatisplus.extension.service.IService} * {@link com.baomidou.mybatisplus.extension.service.impl.ServiceImpl} */ public interface RootMapper<T> extends BaseMapper<T> { /** * 自定義批量插入 * 如果要自動(dòng)填充,@Param(xx) xx參數(shù)名必須是 list/collection/array 3個(gè)的其中之一 */ int insertBatch(@Param("list") List<T> list); /** * 自定義批量更新,條件為主鍵 * 如果要自動(dòng)填充,@Param(xx) xx參數(shù)名必須是 list/collection/array 3個(gè)的其中之一 */ int updateBatch(@Param("list") List<T> list); }
@Repository public interface UserInfoMapper extends RootMapper<UserInfo> { } public interface UserInfoService extends IService<UserInfo> { int saveAll(); int updateAll(); } @Service public 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添加真正的批量新增、批量更新的實(shí)現(xiàn)方法”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。