springBoot集成mybatis 轉(zhuǎn)換為 mybatis-plus方式
更新時間:2021年12月03日 11:39:57 投稿:jingxian
這篇文章主要介紹了springBoot集成mybatis 轉(zhuǎn)換為 mybatis-plus方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
導(dǎo)入maven
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency>
更新yml文件
#mybatis-plus mybatis-plus: mapperPackage: com.xn.mapper typeAliasesPackage: com.xn.mapper mapperLocations: classpath:mapper/*.xml global-config: db-config: id-type: none configuration: # 字段下劃線轉(zhuǎn)駝峰 map-underscore-to-camel-case: false log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
添加擴(kuò)展文件
(用于擴(kuò)展 分頁/批量新增修改/更多的方法修改 基礎(chǔ)可以不加)

BaseEntity 用于定義model
model繼承后可以 id自增會回填,更新時間在修改時刷新,創(chuàng)建時間在創(chuàng)建時刷新
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.SuperBuilder;
import java.io.Serializable;
import java.util.Date;
@Getter
@Setter
@SuperBuilder
@NoArgsConstructor
@AllArgsConstructor
public abstract class BaseEntity implements Serializable {
/**
* 創(chuàng)建時間 自增方式
*/
@TableField(fill = FieldFill.INSERT)
public Date create_time;
/**
* 更新時間
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
public Date update_time;
/**
* ID
*/
@TableId(value="id" ,type = IdType.AUTO)
private Long id;
}
CreateAndUpdateMetaObjectHandler
設(shè)置刷新 更新時間 創(chuàng)建時間
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import java.util.Date;
/**
* MP注入處理器
*/
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {
public String CREATE_TIME = "create_time";
public String UPDATE_TIME = "update_time";
@Override
public void insertFill(MetaObject metaObject) {
if (metaObject.hasGetter(CREATE_TIME)) {
if (metaObject.getValue(CREATE_TIME) == null) {
this.setFieldValByName(CREATE_TIME, new Date(), metaObject);
}
}
}
@Override
public void updateFill(MetaObject metaObject) {
if (metaObject.hasGetter(UPDATE_TIME)) {
if (metaObject.getValue(UPDATE_TIME) == null) {
this.setFieldValByName(UPDATE_TIME, new Date(), metaObject);
}
}
}
}
批量插入/更新 mapper需要繼承這個接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
/**
* 自定義 Mapper 接口, 實現(xiàn) 自定義擴(kuò)展
*
*/
public interface BaseMapperPlus<T> extends BaseMapper<T> {
/**
* 批量插入(mysql)
* @param entityList
* @return
*/
Integer insertBatchSomeColumn(List<T> entityList);
/**
* 批量更新(mysql)
* @param entityList
* @return
*/
Integer updateBatchSomeColumn(List<T> entityList);
}
將批量方法放到 sql注入器中
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.extension.injector.methods.InsertBatchSomeColumn;
import java.util.List;
/**
* mybatis + sql注入器
*/
public class MybatisPlusSqlInjector extends DefaultSqlInjector {
@Override
public List<AbstractMethod> getMethodList(Class<?> mapperClass) {
List<AbstractMethod> methodList = super.getMethodList(mapperClass);
// 添加InsertBatchSomeColumn方法
methodList.add(new InsertBatchSomeColumn());
methodList.add(new UpdateBatchSomeColumn());
return methodList;
}
實現(xiàn)批量更新的方法
import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
/**
* 批處理更新一些列
*
*/
public class UpdateBatchSomeColumn 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);
SqlSource sqlSource = languageDriver.createSqlSource(configuration, sqlResult, modelClass);
return this.addUpdateMappedStatement(mapperClass, modelClass, "updateBatchSomeColumn", sqlSource);
}
}
mybatis-plus配置類
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* mybatis-plus配置類
*/
@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
@MapperScan("${mybatis-plus.mapperPackage}")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分頁插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 樂觀鎖插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
return interceptor;
}
/**
* 分頁插件,自動識別數(shù)據(jù)庫類型
*/
public PaginationInnerInterceptor paginationInnerInterceptor() {
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 設(shè)置數(shù)據(jù)庫類型為mysql
paginationInnerInterceptor.setDbType(DbType.MYSQL);
// 設(shè)置最大單頁限制數(shù)量,默認(rèn) 500 條,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
return paginationInnerInterceptor;
}
/**
* 樂觀鎖插件
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() {
return new OptimisticLockerInnerInterceptor();
}
/**
* 元對象字段填充控制器
*/
@Bean
public MetaObjectHandler metaObjectHandler() {
return new CreateAndUpdateMetaObjectHandler();
}
/**
* sql注入器配置
*/
@Bean
public MybatisPlusSqlInjector easySqlInjector () {
return new MybatisPlusSqlInjector();
}
}
還有兩個是分頁與查詢方式可以自己定義
分頁類需要繼承 IPage,查詢類可以繼承 IService
開始測試
使用分頁查詢
@Override
public ServerResponse selectTableTestList(TableTestPOJO tableTest) {
// 分頁查詢 1 sql自己寫 適用于多表
Page<TableTest> page = new Page<>(mutualStep.getPageNum(), mutualStep.getPageSize());
page = tableTestMapper.findTableList(page,new TableTest());
// 分頁查詢 2 對象篩選 適用單表 條件默認(rèn)相等
QueryWrapper<TableTest> query = Wrappers.query();
query.like("name","ls");
query.and(
wrapper ->
wrapper.notLike("name","1").or().like("name","ls")
);
query.orderByDesc("id");
Page<TableTest> page = new Page<>(tableTest.getPageNum(), tableTest.getPageSize());
Page<TableTest> pageList = tableTestMapper.selectPage(page, query);
return ServerResponse.createBySuccess(pageList);
}
邏輯刪除定義
/**
* 刪除狀態(tài) 0未刪除,1刪除
*/
@TableLogic(value = "0",delval = "1")
private Integer is_del;
邏輯刪除
@Override
public ServerResponse deleteTableTest(MutualStepPage mutualStepPage, Integer... ids) {
int number = tableTestMapper.deleteBatchIds(Arrays.asList(ids));
return ServerResponse.createBySuccess(number);
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot和Swagger結(jié)合提高API開發(fā)效率
這篇文章主要介紹了SpringBoot和Swagger結(jié)合提高API開發(fā)效率的相關(guān)資料,需要的朋友可以參考下2017-09-09
Java 數(shù)組復(fù)制clone方法實現(xiàn)詳解
這篇文章主要介紹了Java 數(shù)組復(fù)制clone方法實現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11

