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ò)展 分頁(yè)/批量新增修改/更多的方法修改 基礎(chǔ)可以不加)
BaseEntity 用于定義model
model繼承后可以 id自增會(huì)回填,更新時(shí)間在修改時(shí)刷新,創(chuàng)建時(shí)間在創(chuàng)建時(shí)刷新
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)建時(shí)間 自增方式 */ @TableField(fill = FieldFill.INSERT) public Date create_time; /** * 更新時(shí)間 */ @TableField(fill = FieldFill.INSERT_UPDATE) public Date update_time; /** * ID */ @TableId(value="id" ,type = IdType.AUTO) private Long id; }
CreateAndUpdateMetaObjectHandler
設(shè)置刷新 更新時(shí)間 創(chuàng)建時(shí)間
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需要繼承這個(gè)接口
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import java.util.List; /** * 自定義 Mapper 接口, 實(shí)現(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; }
實(shí)現(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(); // 分頁(yè)插件 interceptor.addInnerInterceptor(paginationInnerInterceptor()); // 樂(lè)觀鎖插件 interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor()); return interceptor; } /** * 分頁(yè)插件,自動(dòng)識(shí)別數(shù)據(jù)庫(kù)類型 */ public PaginationInnerInterceptor paginationInnerInterceptor() { PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); // 設(shè)置數(shù)據(jù)庫(kù)類型為mysql paginationInnerInterceptor.setDbType(DbType.MYSQL); // 設(shè)置最大單頁(yè)限制數(shù)量,默認(rèn) 500 條,-1 不受限制 paginationInnerInterceptor.setMaxLimit(-1L); return paginationInnerInterceptor; } /** * 樂(lè)觀鎖插件 */ public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor() { return new OptimisticLockerInnerInterceptor(); } /** * 元對(duì)象字段填充控制器 */ @Bean public MetaObjectHandler metaObjectHandler() { return new CreateAndUpdateMetaObjectHandler(); } /** * sql注入器配置 */ @Bean public MybatisPlusSqlInjector easySqlInjector () { return new MybatisPlusSqlInjector(); } }
還有兩個(gè)是分頁(yè)與查詢方式可以自己定義
分頁(yè)類需要繼承 IPage,查詢類可以繼承 IService
開(kāi)始測(cè)試
使用分頁(yè)查詢
@Override public ServerResponse selectTableTestList(TableTestPOJO tableTest) { // 分頁(yè)查詢 1 sql自己寫(xiě) 適用于多表 Page<TableTest> page = new Page<>(mutualStep.getPageNum(), mutualStep.getPageSize()); page = tableTestMapper.findTableList(page,new TableTest()); // 分頁(yè)查詢 2 對(duì)象篩選 適用單表 條件默認(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); }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java詳細(xì)分析連接數(shù)據(jù)庫(kù)的流程
Java數(shù)據(jù)庫(kù)連接,JDBC是Java語(yǔ)言中用來(lái)規(guī)范客戶端程序如何來(lái)訪問(wèn)數(shù)據(jù)庫(kù)的應(yīng)用程序接口,提供了諸如查詢和更新數(shù)據(jù)庫(kù)中數(shù)據(jù)的方法。JDBC也是Sun Microsystems的商標(biāo)。我們通常說(shuō)的JDBC是面向關(guān)系型數(shù)據(jù)庫(kù)的2022-05-05SpringBoot和Swagger結(jié)合提高API開(kāi)發(fā)效率
這篇文章主要介紹了SpringBoot和Swagger結(jié)合提高API開(kāi)發(fā)效率的相關(guān)資料,需要的朋友可以參考下2017-09-09Java 數(shù)組復(fù)制clone方法實(shí)現(xiàn)詳解
這篇文章主要介紹了Java 數(shù)組復(fù)制clone方法實(shí)現(xiàn)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11Awaitility同步異步工具實(shí)戰(zhàn)示例詳解
這篇文章主要為大家介紹了Awaitility同步異步工具實(shí)戰(zhàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08Springboot整合thymleaf模板引擎過(guò)程解析
這篇文章主要介紹了Springboot整合thymleaf模板引擎過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11