springBoot集成mybatis|springBoot集成mybatis 转换为 mybatis-plus方式

目录

  • 导入maven
  • 更新yml文件
  • 添加扩展文件
    • BaseEntity 用于定义model
    • CreateAndUpdateMetaObjectHandler
    • 批量插入/更新 mapper需要继承这个接口
    • 将批量方法放到 sql注入器中
    • 实现批量更新的方法
    • mybatis-plus配置类
  • 开始测试
    • 使用分页查询
    • 逻辑删除定义
    • 逻辑删除
mybatis-plus官方

导入maven
com.baomidoumybatis-plus-boot-starter3.4.2


更新yml文件
#mybatis-plusmybatis-plus: mapperPackage: com.xn.mapper typeAliasesPackage: com.xn.mapper mapperLocations: classpath:mapper/*.xml global-config:db-config:id-type: none configuration:# 字段下划线转驼峰map-underscore-to-camel-case: falselog-impl: org.apache.ibatis.logging.stdout.StdOutImpl


添加扩展文件 (用于扩展 分页/批量新增修改/更多的方法修改 基础可以不加)
【springBoot集成mybatis|springBoot集成mybatis 转换为 mybatis-plus方式】springBoot集成mybatis|springBoot集成mybatis 转换为 mybatis-plus方式
文章图片


BaseEntity 用于定义model
model继承后可以 id自增会回填,更新时间在修改时刷新,创建时间在创建时刷新
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@AllArgsConstructorpublic abstract class BaseEntity implements Serializable {/*** 创建时间 自增方式*/@TableField(fill = FieldFill.INSERT)public Date create_time; /*** 更新时间*/@TableField(fill = FieldFill.INSERT_UPDATE)public Date update_time; /*** ID*/@TableId(value="https://www.it610.com/article/id" ,type = IdType.AUTO)private Long id; }


CreateAndUpdateMetaObjectHandler
设置刷新 更新时间 创建时间
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 接口, 实现 自定义扩展 * */public interface BaseMapperPlus extends BaseMapper {/*** 批量插入(mysql)* @param entityList* @return*/Integer insertBatchSomeColumn(List entityList); /*** 批量更新(mysql)* @param entityList* @return*/Integer updateBatchSomeColumn(List 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 {@Overridepublic List getMethodList(Class mapperClass) {List methodList = super.getMethodList(mapperClass); // 添加InsertBatchSomeColumn方法methodList.add(new InsertBatchSomeColumn()); methodList.add(new UpdateBatchSomeColumn()); return methodList; }


实现批量更新的方法
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 {@Overridepublic MappedStatement injectMappedStatement(Class mapperClass, Class modelClass, TableInfo tableInfo) {String sql = ""; 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; } /*** 分页插件,自动识别数据库类型*/ public PaginationInnerInterceptor paginationInnerInterceptor() {PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(); // 设置数据库类型为mysqlpaginationInnerInterceptor.setDbType(DbType.MYSQL); // 设置最大单页限制数量,默认 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

开始测试
使用分页查询
@Overridepublic ServerResponse selectTableTestList(TableTestPOJO tableTest) {// 分页查询 1 sql自己写 适用于多表Page page = new Page<>(mutualStep.getPageNum(), mutualStep.getPageSize()); page = tableTestMapper.findTableList(page,new TableTest()); // 分页查询 2 对象筛选 适用单表 条件默认相等QueryWrapper query = Wrappers.query(); query.like("name","ls"); query.and(wrapper ->wrapper.notLike("name","1").or().like("name","ls")); query.orderByDesc("id"); Page page = new Page<>(tableTest.getPageNum(), tableTest.getPageSize()); Page pageList = tableTestMapper.selectPage(page, query); return ServerResponse.createBySuccess(pageList); }


逻辑删除定义
/*** 删除状态 0未删除,1删除*/@TableLogic(value = "https://www.it610.com/article/0",delval = "1")private Integer is_del;


逻辑删除
@Overridepublic ServerResponse deleteTableTest(MutualStepPage mutualStepPage, Integer... ids) {int number = tableTestMapper.deleteBatchIds(Arrays.asList(ids)); return ServerResponse.createBySuccess(number); }

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读