springBoot集成mybatis 轉換為 mybatis-plus方式

mybatis-plus官方

導入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:
  # 字段下劃線轉駝峰
  map-underscore-to-camel-case: false
  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

添加擴展文件

(用於擴展 分頁/批量新增修改/更多的方法修改 基礎可以不加)

在這裡插入圖片描述

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
@AllArgsConstructor
public 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="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<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;
    }

實現批量更新的方法

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;
	}
	/**
	 * 分頁插件,自動識別數據庫類型
	 */
	public PaginationInnerInterceptor paginationInnerInterceptor() {
		PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
		// 設置數據庫類型為mysql
		paginationInnerInterceptor.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

開始測試

使用分頁查詢

    @Override
    public ServerResponse selectTableTestList(TableTestPOJO tableTest) {
        // 分頁查詢 1 sql自己寫 適用於多表
        Page<TableTest> page = new Page<>(mutualStep.getPageNum(), mutualStep.getPageSize());
        page = tableTestMapper.findTableList(page,new TableTest());
        // 分頁查詢 2 對象篩選 適用單表 條件默認相等
        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);
    }

邏輯刪除定義

	/**
     * 刪除狀態 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);
    }

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: