本篇內容介紹了“mybatisplus批量插入修改的方法是什么”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠學有所成!
IService 的實現類 ServiceImpl 中截取一段代碼
/**
* 批量插入
*
* @param entityList ignore
* @param batchSize ignore
* @return ignore
*/
@Transactional(rollbackFor = Exception.class)
@Override
public boolean saveBatch(Collection<T> entityList, int batchSize){
String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE);
return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity));
}會發現,其實是在循環插入, 那么如果這樣我們有兩種選擇
1 使用mybatis 的xml文件,自己拼接插入,修改語句,就像最原始的那樣,通過<foreach 標簽實現
2 重新配置全局的批量修改,增加方法
第一種不再贅述,現在說明第二種用法
一共需要五步;
第一步: 一般引入mybaits-plus 都會有相應的配置類, MybatisPlusConfig 名字無所謂,作用是一樣的,一般都會用自帶的分頁插件,可以在此基礎上,繼續添加,給出我的配置
// 分頁差距
@Configuration
public class MybatisPlusConfig {
@Bean
@ConditionalOnMissingBean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor paginationInterceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor= new PaginationInnerInterceptor(DbType.MYSQL);
paginationInterceptor.addInnerInterceptor(paginationInnerInterceptor);
return paginationInterceptor;
}
/**
* 自動填充功能
* @return
*/
@Bean
@ConditionalOnMissingBean
public GlobalConfig globalConfig(){
GlobalConfig globalConfig = new GlobalConfig();
// globalConfig.setMetaObjectHandler(new MybatisMetaObjectHandler());
return globalConfig;
}
// 自定義sql注入器
@Bean
public CustomizedSqlInjector customizedSqlInjector(){
return new CustomizedSqlInjector();
}
}第二步,創建自定義sql注入器
/**
* 自定義方法SQL注入器
*/
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;
}
}第三步: 創建一個類似于mybaits-plus 中的 BaseMapper的一個接口,我這里叫做RootMapper ,然后繼承BaseMapper ,并新增兩個批量操作方法, insertBatch updateBatch
/**
* @Description 使用的時候,只需要繼承RootMapper即可
* @Author FL
* @Date 13:43 2022/5/5
* @Param
**/
public interface RootMapper<T> extends BaseMapper<T> {
/**
* 自定義批量插入
* 如果要自動填充,@Param(xx) xx參數名必須是 list/collection/array 3個的其中之一
*/
int insertBatch(@Param("list") List<T> list);
/**
* 自定義批量更新,條件為主鍵
* 如果要自動填充,@Param(xx) xx參數名必須是 list/collection/array 3個的其中之一
*/
int updateBatch(@Param("list") List<T> list);
}第四步: 分別創建上述兩個方法的具體實現類
@Slf4j
public class InsertBatchMethod extends AbstractMethod {
/**
* insert into user(id, name, age) values (1, "a", 17), (2, "b", 18);
<script>
insert into user(id, name, age) values
<foreach collection="list" item="item" index="index" open="(" separator="),(" close=")">
#{item.id}, #{item.name}, #{item.age}
</foreach>
</script>
*/
@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);
// 第三個參數必須和RootMapper的自定義方法名一致
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();
}
}
=============================================================================
/**
* 批量更新方法實現,條件為主鍵,選擇性更新
*/
@Slf4j
public class UpdateBatchMethod extends AbstractMethod {
/**
* update user set name = "a", age = 17 where id = 1;
* update user set name = "b", age = 18 where id = 2;
<script>
<foreach collection="list" item="item" separator=";">
update user
<set>
<if test="item.name != null and item.name != ''">
name = #{item.name,jdbcType=VARCHAR},
</if>
<if test="item.age != null">
age = #{item.age,jdbcType=INTEGER},
</if>
</set>
where id = #{item.id,jdbcType=INTEGER}
</foreach>
</script>
*/
@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);
}
}第五步: 使用,將原有的繼承BaseMapper的方法,改寫為繼承RootMapper ,后續批量操作,直接使用新增的兩個方法進行處理即可
“mybatisplus批量插入修改的方法是什么”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識可以關注億速云網站,小編將為大家輸出更多高質量的實用文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。