简介
Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
我们的愿景是成为Mybatis最好的搭档,就像 Contra Game 中的1P、2P,基友搭配,效率翻倍。
特性
代码托管
Github|OSChina
参与贡献
欢迎各路好汉一起来参与完善Mybatis-Plus,我们期待你的PR!
假设我们已存在一张 User 表,且已有对应的实体类 User,实现 User 表的 CRUD 操作我们需要做什么呢?
/** User 对应的 Mapper 接口 */
public interface UserMapper extends BaseMapper<User> { }
以上就是您所需的所有操作,甚至不需要您创建XML文件,我们如何使用它呢?
基本CRUD
// 初始化 影响行数
int result = 0;
// 初始化 User 对象
User user = new User();// 插入 User (插入成功会自动回写主键到实体类)
user.setName("Tom");
result = userMapper.insert(user);// 更新 User
user.setAge(18);
result = userMapper.updateById(user);// 查询 User
User exampleUser = userMapper.selectById(user.getId());// 查询姓名为‘张三’的所有用户记录
List<User> userList = userMapper.selectList(new EntityWrapper<User>().eq("name", "张三")
);// 删除 User
result = userMapper.deleteById(user.getId());
以上是基本的 CRUD 操作,当然我们可用的 API 远不止这几个,我们提供了多达 17 个方法给大家使用,可以极其方便的实现单一、批量、分页等操作,接下来我们就来看看 MP 是如何使用分页的。
分页操作
// 分页查询 10 条姓名为‘张三’的用户记录
List<User> userList = userMapper.selectPage(new Page<User>(1, 10),new EntityWrapper<User>().eq("name", "张三")
);
如您所见,我们仅仅需要继承一个 BaseMapper 即可实现大部分单表 CRUD 操作,极大的减少的开发负担。
有人也许会质疑:这难道不是通用 Mapper 么?别急,咱们接着往下看。
现有一个需求,我们需要分页查询 User 表中,年龄在18~50之间性别为男且姓名为张三的所有用户,这时候我们该如何实现上述需求呢?
传统做法是 Mapper 中定义一个方法,然后在 Mapper 对应的 XML 中填写对应的 SELECT 语句,且我们还要集成分页,实现以上一个简单的需求,往往需要我们做很多重复单调的工作,普通的通用 Mapper 能够解决这类痛点么?
用 MP 的方式打开以上需求
// 分页查询 10 条姓名为‘张三’、性别为男,且年龄在18至50之间的用户记录
List<User> userList = userMapper.selectPage(new Page<User>(1, 10),new EntityWrapper<User>().eq("name", "张三").eq("sex", 0).between("age", "18", "50")
);
以上操作,等价于
SELECT *
FROM sys_user
WHERE (name='张三' AND sex=0 AND age BETWEEN '18' AND '50')
LIMIT 0,10
Mybatis-Plus 通过 EntityWrapper(简称 EW,MP 封装的一个查询条件构造器)或者 Condition(与EW类似) 来让用户自由的构建查询条件,简单便捷,没有额外的负担,能够有效提高开发效率。
ActiveRecord 一直广受动态语言( PHP 、 Ruby 等)的喜爱,而 Java 作为准静态语言,对于 ActiveRecord 往往只能感叹其优雅,所以我们也在 AR 道路上进行了一定的探索,喜欢大家能够喜欢,也同时欢迎大家反馈意见与建议。
我们如何使用 AR 模式?
@TableName("sys_user") // 注解指定表名
public class User extends Model<User> {... // fields... // getter and setter/** 指定主键 */@Overrideprotected Serializable pkVal() {return this.id;}
}
我们仅仅需要继承 Model 类且实现主键指定方法 即可让实体开启 AR 之旅,开启 AR 之路后,我们如何使用它呢?
基本CRUD
// 初始化 成功标识
boolean result = false;
// 初始化 User
User user = new User();// 保存 User
user.setName("Tom");
result = user.insert();// 更新 User
user.setAge(18);
result = user.updateById();// 查询 User
User exampleUser = t1.selectById();// 查询姓名为‘张三’的所有用户记录
List<User> userList1 = user.selectList(new EntityWrapper<User>().eq("name", "张三")
);// 删除 User
result = t2.deleteById();
分页操作
// 分页查询 10 条姓名为‘张三’的用户记录
List<User> userList = user.selectPage(new Page<User>(1, 10),new EntityWrapper<User>().eq("name", "张三")
).getRecords();
复杂操作
// 分页查询 10 条姓名为‘张三’、性别为男,且年龄在18至50之间的用户记录
List<User> userList = user.selectPage(new Page<User>(1, 10),new EntityWrapper<User>().eq("name", "张三").eq("sex", 0).between("age", "18", "50")
).getRecords();
AR 模式提供了一种更加便捷的方式实现 CRUD 操作,其本质还是调用的 Mybatis 对应的方法,类似于语法糖。
通过以上两个简单示例,我们简单领略了 Mybatis-Plus 的魅力与高效率,值得注意的一点是:我们提供了强大的代码生成器,可以快速生成各类代码,真正的做到了即开即用。
查询最高版本或历史版本方式:Maven中央库 | Maven阿里库
Mybatis-Plus 的集成非常简单,对于 Spring,我们仅仅需要把 Mybatis 自带的MybatisSqlSessionFactoryBean替换为 MP 自带的即可。
MP 大部分配置都和传统 Mybatis 一致,少量配置为 MP 特色功能配置,此处仅对 MP 的特色功能进行讲解,其余请参考 Mybatis-Spring 配置说明。
示例工程:
mybatisplus-spring-mvc
mybatisplus-spring-boot
PostgreSql 自定义 SQL 注入器
sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
示例代码:
XML 配置
详细配置可参考参数说明中的 MybatisSqlSessionFactoryBean 和 GlobalConfiguration
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"><!-- 配置数据源 --><property name="dataSource" ref="dataSource"/><!-- 自动扫描 Xml 文件位置 --><property name="mapperLocations" value="classpath:mybatis/*/*.xml"/><!-- 配置 Mybatis 配置文件(可无) --><property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/><!-- 配置包别名,支持通配符 * 或者 ; 分割 --><property name="typeAliasesPackage" value="com.baomidou.springmvc.model"/><!-- 枚举属性配置扫描,支持通配符 * 或者 ; 分割 --><property name="typeEnumsPackage" value="com.baomidou.springmvc.entity.*.enums"/><!-- 以上配置和传统 Mybatis 一致 --><!-- 插件配置 --><property name="plugins"><array><!-- 分页插件配置, 参考文档分页插件部分!! --><!-- 如需要开启其他插件,可配置于此 --></array></property><!-- MP 全局配置注入 --><property name="globalConfig" ref="globalConfig"/>
</bean><!-- 定义 MP 全局策略 -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"><!-- 主键策略配置 --><!-- 可选参数AUTO->`0`("数据库ID自增")INPUT->`1`(用户输入ID")ID_WORKER->`2`("全局唯一ID")UUID->`3`("全局唯一ID")--><property name="idType" value="2"/><!-- 数据库类型配置 --><!-- 可选参数(默认mysql)MYSQL->`mysql`ORACLE->`oracle`DB2->`db2`H2->`h2`HSQL->`hsql`SQLITE->`sqlite`POSTGRE->`postgresql`SQLSERVER2005->`sqlserver2005`SQLSERVER->`sqlserver`--><property name="dbType" value="oracle"/><!-- 全局表为下划线命名设置 true --><property name="dbColumnUnderline" value="true"/>
</bean>
特别注意 MybatisSqlSessionFactoryBean 非原生的类,必须如上配置 !
Java Config
Java EE(J2EE)快速开发框架 SpringWind
Mybatis,SSM 后台框架 KangarooAdmin
JAVA分布式快速开发基础平台 iBase4J
mybatisplus乐观锁,又一个 SSM 后台管理框架 framework
猫宁Morning公益商城 Morning
基础权限开发框架 BMS Shiro 案例
简单实用的权限系统 spring-shiro-training Shiro 案例
系统管理中心系统 center
Springboot-Shiro 脚手架 skeleton
Springboot-Shiro 美女图片爬虫 springboot_mybatisplus
guns 后台管理系统 guns
maple 企业信息化的开发基础平台 maple
JeeWeb敏捷开发平台 jeeweb-mybatis
CMS 平台 youngcms
前后端分离的基础权限管理后台 king-admin
前后端分离 Vue 快速开发平台 jeefast
SpringBoot + Shiro +FreeMarker 制作的通用权限管理 bing-upms
SpringBoot 企业级快速开发脚手架 slife
在代码生成之前,首先进行配置,MP提供了大量的自定义设置,生成的代码完全能够满足各类型的需求,如果你发现配置不能满足你的需求,欢迎提交issue和pull-request,有兴趣的也可以查看源码进行了解。
参数说明
参数相关的配置,详见源码
主键策略选择
MP支持以下4中主键策略,可根据需求自行选用:
值 | 描述 |
---|---|
IdType.AUTO | 数据库ID自增 |
IdType.INPUT | 用户输入ID |
IdType.ID_WORKER | 全局唯一ID,内容为空自动填充(默认配置) |
IdType.UUID | 全局唯一ID,内容为空自动填充 |
AUTO、INPUT和UUID大家都应该能够明白,这里主要讲一下ID_WORKER。首先得感谢开源项目Sequence,感谢作者李景枫。
什么是Sequence?简单来说就是一个分布式高效有序ID生产黑科技工具,思路主要是来源于Twitter-Snowflake算法。这里不详细讲解Sequence,有兴趣的朋友请[点此去了解Sequence(http://git.oschina.net/yu120/sequence)。
MP在Sequence的基础上进行部分优化,用于产生全局唯一ID,好的东西希望推广给大家,所以我们将ID_WORDER设置为默认配置。
表及字段命名策略选择
在MP中,我们建议数据库表名采用下划线命名方式,而表字段名采用驼峰命名方式。
这么做的原因是为了避免在对应实体类时产生的性能损耗,这样字段不用做映射就能直接和实体类对应。当然如果项目里不用考虑这点性能损耗,那么你采用下滑线也是没问题的,只需要在生成代码时配置dbColumnUnderline属性就可以。
如何生成代码
方式一、代码生成
<!-- 模板引擎 -->
<dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.0</version>
</dependency><!-- MP 核心库 -->
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus</artifactId><version>最新版本</version>
</dependency>
代码生成、示例一
import java.util.HashMap;
import java.util.Map;import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;/*** <p>* 代码生成器演示* </p>*/
public class MpGenerator {/*** <p>* MySQL 生成演示* </p>*/public static void main(String[] args) {AutoGenerator mpg = new AutoGenerator();// 全局配置GlobalConfig gc = new GlobalConfig();gc.setOutputDir("D://");gc.setFileOverride(true);gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为falsegc.setEnableCache(false);// XML 二级缓存gc.setBaseResultMap(true);// XML ResultMapgc.setBaseColumnList(false);// XML columList// .setKotlin(true) 是否生成 kotlin 代码gc.setAuthor("Yanghu");// 自定义文件命名,注意 %s 会自动填充表实体属性!// gc.setMapperName("%sDao");// gc.setXmlName("%sDao");// gc.setServiceName("MP%sService");// gc.setServiceImplName("%sServiceDiy");// gc.setControllerName("%sAction");mpg.setGlobalConfig(gc);// 数据源配置DataSourceConfig dsc = new DataSourceConfig();dsc.setDbType(DbType.MYSQL);dsc.setTypeConvert(new MySqlTypeConvert(){// 自定义数据库表字段类型转换【可选】@Overridepublic DbColumnType processTypeConvert(String fieldType) {System.out.println("转换类型:" + fieldType);// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。return super.processTypeConvert(fieldType);}});dsc.setDriverName("com.mysql.jdbc.Driver");dsc.setUsername("root");dsc.setPassword("521");dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis-plus?characterEncoding=utf8");mpg.setDataSource(dsc);// 策略配置StrategyConfig strategy = new StrategyConfig();// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略// strategy.setInclude(new String[] { "user" }); // 需要生成的表// strategy.setExclude(new String[]{"test"}); // 排除生成的表// 自定义实体父类// strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");// 自定义实体,公共字段// strategy.setSuperEntityColumns(new String[] { "test_id", "age" });// 自定义 mapper 父类// strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");// 自定义 service 父类// strategy.setSuperServiceClass("com.baomidou.demo.TestService");// 自定义 service 实现类父类// strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");// 自定义 controller 父类// strategy.setSuperControllerClass("com.baomidou.demo.TestController");// 【实体】是否生成字段常量(默认 false)// public static final String ID = "test_id";// strategy.setEntityColumnConstant(true);// 【实体】是否为构建者模型(默认 false)// public User setName(String name) {this.name = name; return this;}// strategy.setEntityBuilderModel(true);mpg.setStrategy(strategy);// 包配置PackageConfig pc = new PackageConfig();pc.setParent("com.baomidou");pc.setModuleName("test");mpg.setPackageInfo(pc);// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】InjectionConfig cfg = new InjectionConfig() {@Overridepublic void initMap() {Map<String, Object> map = new HashMap<String, Object>();map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");this.setMap(map);}};// 自定义 xxList.jsp 生成List<FileOutConfig> focList = new ArrayList<FileOutConfig>();focList.add(new FileOutConfig("/template/list.jsp.vm") {@Overridepublic String outputFile(TableInfo tableInfo) {// 自定义输入文件名称return "D://my_" + tableInfo.getEntityName() + ".jsp";}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 调整 xml 生成目录演示focList.add(new FileOutConfig("/templates/mapper.xml.vm") {@Overridepublic String outputFile(TableInfo tableInfo) {return "/develop/code/xml/" + tableInfo.getEntityName() + ".xml";}});cfg.setFileOutConfigList(focList);mpg.setCfg(cfg);// 关闭默认 xml 生成,调整生成 至 根目录TemplateConfig tc = new TemplateConfig();tc.setXml(null);mpg.setTemplate(tc);// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称// TemplateConfig tc = new TemplateConfig();// tc.setController("...");// tc.setEntity("...");// tc.setMapper("...");// tc.setXml("...");// tc.setService("...");// tc.setServiceImpl("...");// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。// mpg.setTemplate(tc);// 执行生成mpg.execute();// 打印注入设置【可无】System.err.println(mpg.getCfg().getMap().get("abc"));}}
代码生成、示例二
new AutoGenerator().setGlobalConfig(...
).setDataSource(...
).setStrategy(...
).setPackageInfo(...
).setCfg(...
).setTemplate(...
).execute();
其他方式、 Maven插件生成
待补充(Maven代码生成插件 待完善) http://git.oschina.net/baomidou/mybatisplus-maven-plugin
实体无注解化设置,表字段如下规则,主键叫 id 可无注解大写小如下规则。
1、驼峰命名 【 无需处理 】
2、全局配置: 下划线命名 dbColumnUnderline 设置 true , 大写 isCapitalMode 设置 true
表名注解 @TableName
值 | 描述 |
---|---|
value | 表名( 默认空 ) |
resultMap | xml 字段映射 resultMap ID |
主键注解 @TableId
值 | 描述 |
---|---|
value | 字段值(驼峰命名方式,该值可无) |
type | 主键 ID 策略类型( 默认 INPUT ,全局开启的是 ID_WORKER ) |
字段注解 @TableField
值 | 描述 |
---|---|
value | 字段值(驼峰命名方式,该值可无) |
el | 是否为数据库表字段( 默认 true 存在,false 不存在 ) |
exist | 是否为数据库表字段( 默认 true 存在,false 不存在 ) |
strategy | 字段验证 ( 默认 非 null 判断,查看 com.baomidou.mybatisplus.enums.FieldStrategy ) |
fill | 字段填充标记 ( 配合自动填充使用 ) |
序列主键策略 注解 @KeySequence
值 | 描述 |
---|---|
value | 序列名 |
clazz | id的类型 |
乐观锁标记注解 @Version
实体包装器,用于处理 sql 拼接,排序,实体参数查询等!
补充说明: 使用的是数据库字段,不是Java属性!
实体包装器 EntityWrapper 继承 Wrapper
public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) {if (null != entityWrapper) {entityWrapper.orderBy(page.getOrderByField(), page.isAsc());}page.setRecords(baseMapper.selectPage(page, entityWrapper));return page;
}
@Test
public void testTSQL11() {/** 实体带查询使用方法 输出看结果*/EntityWrapper<User> ew = new EntityWrapper<User>();ew.setEntity(new User(1));ew.where("user_name={0}", "'zhangsan'").and("id=1").orNew("user_status={0}", "0").or("status=1").notLike("user_nickname", "notvalue").andNew("new=xx").like("hhh", "ddd").andNew("pwd=11").isNotNull("n1,n2").isNull("n3").groupBy("x1").groupBy("x2,x3").having("x1=11").having("x3=433").orderBy("dd").orderBy("d1,d2");System.out.println(ew.getSqlSegment());
}
int buyCount = selectCount(Condition.create().setSqlSelect("sum(quantity)").isNull("order_id").eq("user_id", 1).eq("type", 1).in("status", new Integer[]{0, 1}).eq("product_id", 1).between("created_time", startDate, currentDate).eq("weal", 1));
mapper java 接口方法
List selectMyPage(RowBounds rowBounds, @Param(“ew”) Wrapper wrapper);
mapper xml 定义
<select id="selectMyPage" resultType="User">SELECT * FROM user <where>${ew.sqlSegment}</where>
</select>
<plugins><!--| 分页插件配置| 插件提供二种方言选择:1、默认方言 2、自定义方言实现类,两者均未配置则抛出异常!| overflowCurrent 溢出总页数,设置第一页 默认false| optimizeType Count优化方式 ( 版本 2.0.9 改为使用 jsqlparser 不需要配置 )| --><!-- 注意!! 如果要支持二级缓存分页使用类 CachePaginationInterceptor 默认、建议如下!! --><plugin interceptor="com.baomidou.mybatisplus.plugins.PaginationInterceptor"><property name="sqlParser" ref="自定义解析类、可以没有" /><property name="localPage" value="默认 false 改为 true 开启了 pageHeper 支持、可以没有" /><property name="dialectClazz" value="自定义方言类、可以没有" /></plugin>
</plugins>
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {/*** 分页插件*/@Beanpublic PaginationInterceptor paginationInterceptor() {return new PaginationInterceptor();}
}
public interface UserMapper{//可以继承或者不继承BaseMapper/*** <p>* 查询 : 根据state状态查询用户列表,分页显示* </p>** @param page* 翻页对象,可以作为 xml 参数直接使用,传递参数 Page 即自动分页* @param state* 状态* @return*/List<User> selectUserList(Pagination page, Integer state);
}
public Page<User> selectUserPage(Page<User> page, Integer state) {page.setRecords(userMapper.selectUserList(page, state));return page;
}
<select id="selectUserList" resultType="User">SELECT * FROM user WHERE state=#{state}
</select>
// 开启分页
PageHelper.startPage(1, 2);
List<User> data = userService.findAll(params);
// 获取总条数
int total = PageHelper.getTotal();
// 获取总条数,并释放资源
int total = PageHelper.freeTotal();
SQL 执行分析拦截器【 目前只支持 MYSQL-5.6.3 以上版本 】,作用是分析 处理 DELETE UPDATE 语句, 防止小白或者恶意 delete update 全表操作!
<plugins><!-- SQL 执行分析拦截器 stopProceed 发现全表执行 delete update 是否停止运行 --><plugin interceptor="com.baomidou.mybatisplus.plugins.SqlExplainInterceptor"><property name="stopProceed" value="false" /></plugin>
</plugins>
注意!参数说明
性能分析拦截器,用于输出每条 SQL 语句及其执行时间
<plugins>....<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 --><plugin interceptor="com.baomidou.mybatisplus.plugins.PerformanceInterceptor"><property name="maxTime" value="100" /><!--SQL是否格式化 默认false--><property name="format" value="true" /></plugin>
</plugins>
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {/*** SQL执行效率插件*/@Bean@Profile({"dev","test"})// 设置 dev test 环境开启public PerformanceInterceptor performanceInterceptor() {return new PerformanceInterceptor();}
}
注意!参数说明
主要使用场景:
意图:
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
<bean class="com.baomidou.mybatisplus.plugins.OptimisticLockerInterceptor"/>
public class User {@Versionprivate Integer version;...
}
特别说明: **仅支持int,Integer,long,Long,Date,Timestamp
示例Java代码
int id = 100;
int version = 2;User u = new User();
u.setId(id);
u.setVersion(version);
u.setXXX(xxx);if(userService.updateById(u)){System.out.println("Update successfully");
}else{System.out.println("Update failed due to modified by others");
}
示例SQL原理
update tbl_user set name='update',version=3 where id=100 and version=2;
开启动态加载 mapper.xml
参数说明:sqlSessionFactory:session工厂mapperLocations:mapper匹配路径enabled:是否开启动态加载 默认:falsedelaySeconds:项目启动延迟加载时间 单位:秒 默认:10ssleepSeconds:刷新时间间隔 单位:秒 默认:20s提供了两个构造,挑选一个配置进入spring配置文件即可:构造1:<bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh"><constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/><constructor-arg name="mapperLocations" value="classpath*:mybatis/mappers/*/*.xml"/><constructor-arg name="enabled" value="true"/></bean>构造2:<bean class="com.baomidou.mybatisplus.spring.MybatisMapperRefresh"><constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/><constructor-arg name="mapperLocations" value="classpath*:mybatis/mappers/*/*.xml"/><constructor-arg name="delaySeconds" value="10"/><constructor-arg name="sleepSeconds" value="20"/><constructor-arg name="enabled" value="true"/></bean>
自定义注入全表删除方法 deteleAll
自定义 MySqlInjector 注入类 java 代码如下:
public class MySqlInjector extends AutoSqlInjector {@Overridepublic void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class<?> mapperClass,Class<?> modelClass, TableInfo table) {/* 添加一个自定义方法 */deleteAllUser(mapperClass, modelClass, table);}public void deleteAllUser(Class<?> mapperClass, Class<?> modelClass, TableInfo table) {/* 执行 SQL ,动态 SQL 参考类 SqlMethod */String sql = "delete from " + table.getTableName();/* mapper 接口方法名一致 */String method = "deleteAll";SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);this.addMappedStatement(mapperClass, method, sqlSource, SqlCommandType.DELETE, Integer.class);}}
当然你的 mapper.java 接口类需要申明使用方法 deleteAll 如下
public interface UserMapper extends BaseMapper<User> {/*** 自定义注入方法*/int deleteAll();}
最后一步注入启动
<!-- 定义 MP 全局策略,安装集成文档部分结合 -->
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">.....<!-- 自定义注入 deleteAll 方法 --><property name="sqlInjector" ref="mySqlInjector" />
</bean><!-- 自定义注入器 -->
<bean id="mySqlInjector" class="com.baomidou.test.MySqlInjector" />
public class User {// 注意!这里需要标记为填充字段@TableField(.. fill = FieldFill.INSERT)private String fillField;....
}
/** 自定义填充公共 name 字段 */
public class MyMetaObjectHandler extends MetaObjectHandler {/*** 测试 user 表 name 字段为空自动填充*/public void insertFill(MetaObject metaObject) {// 更多查看源码测试用例System.out.println("*************************");System.out.println("insert fill");System.out.println("*************************");// 测试下划线Object testType = getFieldValByName("testType", metaObject);//mybatis-plus版本2.0.9+System.out.println("testType=" + testType);if (testType == null) {setFieldValByName("testType", 3, metaObject);//mybatis-plus版本2.0.9+}}@Overridepublic void updateFill(MetaObject metaObject) {//更新填充System.out.println("*************************");System.out.println("update fill");System.out.println("*************************");//mybatis-plus版本2.0.9+setFieldValByName("lastUpdatedDt", new Timestamp(System.currentTimeMillis()), metaObject);}
}
spring 启动注入 MyMetaObjectHandler 配置
<!-- MyBatis SqlSessionFactoryBean 配置 -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean"><property name="globalConfig" ref="globalConfig"></property>
</bean>
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"><!-- 公共字段填充处理器 --><property name="metaObjectHandler" ref="myMetaObjectHandler" />
</bean>
<!-- 自定义处理器 -->
<bean id="myMetaObjectHandler" class="com.baomidou.test.MyMetaObjectHandler" />
1、修改 集成 全局注入器为 LogicSqlInjector
2、全局注入值:
logicDeleteValue // 逻辑删除全局值
logicNotDeleteValue // 逻辑未删除全局值
3、逻辑删除的字段需要注解 @TableLogic
Mybatis-Plus逻辑删除视频教程
@Bean
public GlobalConfiguration globalConfiguration() {GlobalConfiguration conf = new GlobalConfiguration(new LogicSqlInjector());conf.setLogicDeleteValue("-1");conf.setLogicNotDeleteValue("1");conf.setIdType(2);return conf;
}
XML配置方式:
<bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration"><property name="sqlInjector" ref="logicSqlInjector" /><property name="logicDeleteValue" value="-1" /><property name="logicNotDeleteValue" value="1" /><property name="idType" value="2" />
</bean><bean id="logicSqlInjector" class="com.baomidou.mybatisplus.mapper.LogicSqlInjector" />
@TableName("tbl_user")
public class UserLogicDelete {private Long id;...@TableField(value = "delete_flag")@TableLogicprivate Integer deleteFlag;
}
会在mp自带查询和更新方法的sql后面,追加『逻辑删除字段』=『LogicNotDeleteValue默认值』 删除方法: deleteById()和其他delete方法, 底层SQL调用的是update tbl_xxx set 『逻辑删除字段』=『logicDeleteValue默认值』
第一步:扩展Spring的AbstractRoutingDataSource抽象类,实现动态数据源。 AbstractRoutingDataSource中的抽象方法determineCurrentLookupKey是实现数据源的route的核心,这里对该方法进行Override。 【上下文DbContextHolder为一线程安全的ThreadLocal】具体代码如下:
public class DynamicDataSource extends AbstractRoutingDataSource {/*** 取得当前使用哪个数据源* @return*/
@Override
protected Object determineCurrentLookupKey() {return DbContextHolder.getDbType();
}
}public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal<>();/*** 设置数据源* @param dbTypeEnum*/
public static void setDbType(DBTypeEnum dbTypeEnum) {contextHolder.set(dbTypeEnum.getValue());
}/*** 取得当前数据源* @return*/
public static String getDbType() {return contextHolder.get();
}/*** 清除上下文数据*/
public static void clearDbType() {contextHolder.remove();
}
}public enum DBTypeEnum {
one("dataSource_one"), two("dataSource_two");
private String value;DBTypeEnum(String value) {this.value = value;
}public String getValue() {return value;
}
}
第二步:配置动态数据源将DynamicDataSource Bean加入到Spring的上下文xml配置文件中去,同时配置DynamicDataSource的targetDataSources(多数据源目标)属性的Map映射。 代码如下【我省略了dataSource_one和dataSource_two的配置】:
<bean id="dataSource" class="com.miyzh.dataclone.db.DynamicDataSource"><property name="targetDataSources"><map key-type="java.lang.String"><entry key="dataSource_one" value-ref="dataSource_one" /><entry key="dataSource_two" value-ref="dataSource_two" /></map></property><property name="defaultTargetDataSource" ref="dataSource_two" />
</bean>
第三步:使用动态数据源:DynamicDataSource是继承与AbstractRoutingDataSource,而AbstractRoutingDataSource又是继承于org.springframework.jdbc.datasource.AbstractDataSource,AbstractDataSource实现了统一的DataSource接口,所以DynamicDataSource同样可以当一个DataSource使用。
@Test
public void test() {
DbContextHolder.setDbType(DBTypeEnum.one);
List userList = iUserService.selectList(new EntityWrapper());
for (User user : userList) {
log.debug(user.getId() + "#" + user.getName() + "#" + user.getAge());
}DbContextHolder.setDbType(DBTypeEnum.two);List<IdsUser> idsUserList = iIdsUserService.selectList(new EntityWrapper<IdsUser>());for (IdsUser idsUser : idsUserList) {log.debug(idsUser.getMobile() + "#" + idsUser.getUserName());}
}
说明:
实体主键支持Sequence @since 2.0.8
GlobalConfiguration gc = new GlobalConfiguration();//gc.setDbType("oracle");//不需要这么配置了gc.setKeyGenerator(new OracleKeyGenerator());
@TableName("TEST_SEQUSER")
@KeySequence("SEQ_TEST")//类注解
public class TestSequser{@TableId(value = "ID", type = IdType.INPUT)private Long id;}
@KeySequence("SEQ_TEST")
public abstract class Parent{}
public class Child extends Parent{}
以上步骤就可以使用Sequence当主键了。
@Bean
public PaginationInterceptor paginationInterceptor() {PaginationInterceptor paginationInterceptor = new PaginationInterceptor();paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持/** 【测试多租户】 SQL 解析处理拦截器<br>* 这里固定写成住户 1 实际情况你可以从cookie读取,因此数据看不到 【 麻花藤 】 这条记录( 注意观察 SQL )<br>*/List<ISqlParser> sqlParserList = new ArrayList<>();TenantSqlParser tenantSqlParser = new TenantSqlParser();tenantSqlParser.setTenantHandler(new TenantHandler() {@Overridepublic Expression getTenantId() {return new LongValue(1L);}@Overridepublic String getTenantIdColumn() {return "tenant_id";}@Overridepublic boolean doTableFilter(String tableName) {// 这里可以判断是否过滤表/*if ("user".equals(tableName)) {return true;}*/return false;}});sqlParserList.add(tenantSqlParser);paginationInterceptor.setSqlParserList(sqlParserList);paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {@Overridepublic boolean doFilter(MetaObject metaObject) {MappedStatement ms = PluginUtils.getMappedStatement(metaObject);// 过滤自定义查询此时无租户信息约束【 麻花藤 】出现if ("com.baomidou.springboot.mapper.UserMapper.selectListBySQL".equals(ms.getId())) {return true;}return false;}});return paginationInterceptor;
}
枚举属性,必须实现 IEnum 接口如下:
public enum AgeEnum implements IEnum {ONE(1, "一岁"),TWO(2, "二岁");private int value;private String desc;AgeEnum(final int value, final String desc) {this.value = value;this.desc = desc;}@Overridepublic Serializable getValue() {return this.value;}@JsonValue // Jackson 注解,可序列化该属性为中文描述【可无】public String getDesc(){return this.desc;}
}
配置文件 resources/application.yml
mybatis-plus:# 支持统配符 * 或者 ; 分割typeEnumsPackage: com.baomidou.springboot.entity.enums....
MybatisX 辅助 idea 快速开发插件,为效率而生。【入 Q 群 576493122 附件下载! 或者 官方搜索 mybatisx 安装】
mybatis plus官方文档
原文链接: https://blog.csdn.net/helloPurple/article/details/78715508
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态