參考【SpringBoot攻略七渊鞋、集成mybatisplus實戰(zhàn)】,做如下修改:
1瞧挤、自定義sql注入器GeneralMybatisPlusSqlInjector
package com.javasgj.springboot.mybatisplus.config;
import java.util.List;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
/**
* 自定義sql注入器锡宋,增加通用方法
*/
public class GeneralMybatisPlusSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList() {
List<AbstractMethod> methodList = super.getMethodList();
// 根據(jù)id更新所有數(shù)據(jù)
methodList.add(new UpdateAllColumnById());
return methodList;
}
}
2、方法對應(yīng)的實現(xiàn)類UpdateAllColumnById
package com.javasgj.springboot.mybatisplus.config;
import static java.util.stream.Collectors.joining;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
/**
* 根據(jù)id更新所有數(shù)據(jù)
*/
public class UpdateAllColumnById extends AbstractMethod {
@Override
public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
GeneralMybatisPlusSqlMethod sqlMethod = GeneralMybatisPlusSqlMethod.UPDATE_ALL_COLUMN_BY_ID;
String sql = String.format(sqlMethod.getSql(), tableInfo.getTableName(),
sqlSet(false, false, tableInfo, Constants.ENTITY_SPOT),
tableInfo.getKeyColumn(), Constants.ENTITY_SPOT + tableInfo.getKeyProperty(),
new StringBuilder("<if test=\"et instanceof java.util.Map\">")
.append("<if test=\"et.MP_OPTLOCK_VERSION_ORIGINAL!=null\">")
.append(" AND ${et.MP_OPTLOCK_VERSION_COLUMN}=#{et.MP_OPTLOCK_VERSION_ORIGINAL}")
.append("</if></if>"));
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
return addUpdateMappedStatement(mapperClass, modelClass, sqlMethod.getMethod(), sqlSource);
}
@Override
protected String sqlSet(boolean logic, boolean ew, TableInfo table, String prefix) {
String newPrefix = prefix == null ? StringPool.EMPTY : prefix;
String sqlScript = table.getFieldList().stream()
.filter(i -> {
return true;
})
.map(i -> {
return this.getSqlSet(i, newPrefix);
}).collect(joining(StringPool.NEWLINE));
if (ew) {
sqlScript += StringPool.NEWLINE;
sqlScript += SqlScriptUtils.convertIf(SqlScriptUtils.unSafeParam(Constants.U_WRAPPER_SQL_SET),
String.format("%s != null and %s != null", Constants.WRAPPER, Constants.U_WRAPPER_SQL_SET), false);
}
sqlScript = SqlScriptUtils.convertTrim(sqlScript, "SET", null, null, ",");
return sqlScript;
}
public String getSqlSet(TableFieldInfo i, String prefix) {
String newPrefix = prefix == null ? StringPool.EMPTY : prefix;
String column = i.getColumn();
String update = i.getUpdate();
FieldFill fieldFill = i.getFieldFill();
String el = i.getEl();
// 默認(rèn): column=
String sqlSet = column + StringPool.EQUALS;
if (StringUtils.isNotEmpty(update)) {
sqlSet += String.format(update, column);
} else {
sqlSet += SqlScriptUtils.safeParam(newPrefix + el);
}
sqlSet += StringPool.COMMA;
if (fieldFill == FieldFill.UPDATE || fieldFill == FieldFill.INSERT_UPDATE) {
// 不進(jìn)行 if 包裹
return sqlSet;
}
return sqlSet;
}
}
參考其他基本方法的實現(xiàn)類源碼如:UpdateById等等
3特恬、MybatisPlus自定義SQL方法枚舉類GeneralMybatisPlusSqlMethod
package com.javasgj.springboot.mybatisplus.config;
/**
* MybatisPlus自定義SQL方法
*/
public enum GeneralMybatisPlusSqlMethod {
/**
* 修改
*/
UPDATE_ALL_COLUMN_BY_ID("updateAllColumnById", "根據(jù)ID更新所有數(shù)據(jù)", "<script>\nUPDATE %s %s WHERE %s=#{%s} %s\n</script>");
private final String method;
private final String desc;
private final String sql;
GeneralMybatisPlusSqlMethod(String method, String desc, String sql) {
this.method = method;
this.desc = desc;
this.sql = sql;
}
public String getMethod() {
return method;
}
public String getDesc() {
return desc;
}
public String getSql() {
return sql;
}
}
4执俩、MybatisPlus配置類,加載自定義sql注入器
package com.javasgj.springboot.mybatisplus.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
/**
* MybatisPlus配置類
*/
@Configuration
public class MybatisPlusConfig {
/**
* 分頁插件
* 或者在mybatis-config.xml配置:
* <plugins>
* <!-- mybatisplus分頁攔截器 -->
* <plugin interceptor="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
* </plugin>
* </plugins>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
/**
* 自定義sql注入器
* 或者application.properties配置:
* mybatis-plus.globalConfig.sqlInjector=com.javasgj.springboot.mybatisplus.config.GeneralMybatisPlusSqlInjector
*/
@Bean
public ISqlInjector iSqlInjector() {
return new GeneralMybatisPlusSqlInjector();
}
/**
* sql性能分析插件鸵鸥,輸出sql語句及所需時間
*/
/*@Bean
@Profile({"dev","test"})// 設(shè)置 dev test 環(huán)境開啟
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}*/
/**
* 樂觀鎖插件
*/
/*@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}*/
}
5奠滑、自定義基礎(chǔ)Mapper繼承BaseMapper
package com.javasgj.springboot.mybatisplus.dao;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
public interface GeneralBaseMapper<T> extends BaseMapper<T> {
/**
* 根據(jù)id更新所有數(shù)據(jù)
* @param entity
* @return
*/
int updateAllColumnById(@Param(Constants.ENTITY) T entity);
}
6、自定義基礎(chǔ)service繼承IService及實現(xiàn)類
package com.javasgj.springboot.mybatisplus.service;
import java.util.Collection;
import com.baomidou.mybatisplus.extension.service.IService;
public interface GeneralService<T> extends IService<T> {
/**
* 根據(jù)ID更新所有數(shù)據(jù)
* @param entity
* @return
*/
boolean updateAllColumnById(T entity);
/**
* 根據(jù)ID批量更新所有數(shù)據(jù)
* @param entityList
* @return
*/
default boolean updateAllColumnBatchById(Collection<T> entityList) {
return updateAllColumnBatchById(entityList, 30);
}
/**
* 根據(jù)ID批量更新所有數(shù)據(jù)
* @param entityList
* @param batchSize
* @return
*/
boolean updateAllColumnBatchById(Collection<T> entityList, int batchSize);
}
實現(xiàn)類
package com.javasgj.springboot.mybatisplus.service;
import java.util.Collection;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.session.SqlSession;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlHelper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.javasgj.springboot.mybatisplus.config.GeneralMybatisPlusSqlMethod;
import com.javasgj.springboot.mybatisplus.dao.GeneralBaseMapper;
public class GeneralServiceImpl<M extends GeneralBaseMapper<T>, T> extends ServiceImpl<GeneralBaseMapper<T>, T> implements GeneralService<T> {
/**
* 獲取SqlStatement
*
* @param sqlMethod
* @return
*/
protected String sqlStatement(GeneralMybatisPlusSqlMethod generalMybatisPlusSqlMethod) {
return SqlHelper.table(currentModelClass()).getSqlStatement(generalMybatisPlusSqlMethod.getMethod());
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateAllColumnById(T entity) {
return retBool(baseMapper.updateAllColumnById(entity));
}
@Transactional(rollbackFor = Exception.class)
@Override
public boolean updateAllColumnBatchById(Collection<T> entityList, int batchSize) {
if (CollectionUtils.isEmpty(entityList)) {
throw new IllegalArgumentException("Error: entityList must not be empty");
}
int i = 0;
String sqlStatement = sqlStatement(GeneralMybatisPlusSqlMethod.UPDATE_ALL_COLUMN_BY_ID);
try (SqlSession batchSqlSession = sqlSessionBatch()) {
for (T anEntityList : entityList) {
MapperMethod.ParamMap<T> param = new MapperMethod.ParamMap<>();
param.put(Constants.ENTITY, anEntityList);
batchSqlSession.update(sqlStatement, param);
if (i >= 1 && i % batchSize == 0) {
batchSqlSession.flushStatements();
}
i++;
}
batchSqlSession.flushStatements();
}
return true;
}
}
然后所有的mapper和servcie繼承我們自定義擴(kuò)展的基礎(chǔ)mapper和service
好了妒穴,大家開始測試測試吧宋税,參考【原 SpringBoot秘籍七、集成mybatisplus實戰(zhàn)】