亲宝软件园·资讯

展开

springBoot集成mybatis转mybatis-plus

人气:0

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);
    }

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

加载全部内容

相关教程
猜你喜欢
用户评论