广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springBoot集成mybatis转换为mybatis-plus方式
  • 949
分享到

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

2024-04-02 19:04:59 949人浏览 安东尼

Python 官方文档:入门教程 => 点击学习

摘要

目录导入Maven更新yml文件添加扩展文件BaseEntity 用于定义modelCreateAndUpdateMetaObjectHandler批量插入/更新 mapper需要继

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
    @TableField(fill = FieldFill.INSERT)
    public Date create_time;
    
    @TableField(fill = FieldFill.INSERT_UPDATE)
    public Date update_time;
    
    @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;

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;

public interface BaseMapperPlus<T> extends BaseMapper<T> {
    
    Integer insertBatchSomeColumn(List<T> entityList);
    
    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;

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;

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

逻辑删除定义


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

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

--结束END--

本文标题: springBoot集成mybatis转换为mybatis-plus方式

本文链接: https://www.lsjlt.com/news/159086.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作