在本文中,我们将详细介绍【主流技术】MybatisPlus的理解与应用的各个方面,并为您提供关于mybatis-plus的作用的相关解答,同时,我们也将为您带来关于FluentMybatis,原生My
在本文中,我们将详细介绍【主流技术】Mybatis Plus的理解与应用的各个方面,并为您提供关于mybatis-plus的作用的相关解答,同时,我们也将为您带来关于Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比、Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比、java-mybaits-015-mybatis逆向工程最佳实践【基础mybatis-generator、tk.mybatis、mubatis-plus】、mybatis-plus - MybatisPlusAutoConfiguration的有用知识。
本文目录一览:- 【主流技术】Mybatis Plus的理解与应用(mybatis-plus的作用)
- Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比
- Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比
- java-mybaits-015-mybatis逆向工程最佳实践【基础mybatis-generator、tk.mybatis、mubatis-plus】
- mybatis-plus - MybatisPlusAutoConfiguration
【主流技术】Mybatis Plus的理解与应用(mybatis-plus的作用)
前言
mybatis plus是一个mybatis的增强工具,在其基础上只做增强不做改变。作为开发中常见的第三方组件,学习并应用在项目中可以节省开发时间,提高开发效率。
官方文档地址:MyBatis-Plus (baomidou.com)
一、特性
1.1损耗小
自动注入基本CRUD,性能无损耗,直接面向对象操作(通过BaseMaper<约定的泛型>);
1.2支持lambda表达式
通过lambda表达式的形式,方便编写各类查询条件,无需担心字段出错;
1.3支持主键自动生成
内含分布式唯一ID生成器-Squence,可自行配置主键;
1.4支持ActiveRecord模式
实体类只需继承Model类即可进行CRUD操作;
1.5支持分页插件
基于mybatis物理分页,配置好插件后自动将数据分页;
二、快速入门
2.1创建数据库
2.1.1建表
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
2.1.2初始化项目
- 导入依赖(尽量不要与mybatis一起导入)
- 配置依赖
- 编写代码
- 拓展技术能力
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
2.1.3连接数据库
#MysqL配置
#数据库用户名
spring.datasource.username=root
#登录密码
spring.datasource.password=password123
#JDBC地址、编码、安全连接
spring.datasource.url=jdbc:MysqL://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8
#数据库驱动
spring.datasource.driver-class-name=com.MysqL.cj.jdbc.Driver
2.2编写代码
2.2.1实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
//用户id
private Long id;
//用户名
private String name;
//年龄
private Integer age;
//邮箱
private String email;
}
2.2.2mapper文件
@Mapper
@Repository
//该接口继承BaseMapper类所有方法
public interface UserMapper extends BaseMapper<User> {
}
2.2.3逻辑实现层
@Autowired
private UserMapper userMapper;
//创建条件构造器
QueryWrapper<User> wrapper = new QueryWrapper<>();
userMapper.selectList(wrapper);
2.3日志配置
#mybatis-plus日志配置,默认控制台输出日志,properties文件
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
2.4CRUD扩展
2.4.1插入操作(insert)
void insert(){
User user = new User();
user.setName("Alex");
user.setAge(42);
user.setEmail("4353435@qq.com");
//受影响的行数
int result = userMapper.insert(user);
System.out.println(result);
System.out.println(user);
}
主键生成策略
实体类声明数据库表名,同时设置主键id为自增。
//数据库表名
@TableName("user")
public class User implements Serializable {
//用户id,主键自增
@TableId(value = "id",type = IdType.AUTO)
private Long id;
}
2.4.2更新操作(update)
//更新操作
@Test
void updatetest(){
User user = new User();
user.setId(3L);
user.setName("docker&K8s");
//操作结果条数
int i = userMapper.updateById(user);
System.out.println(i);
}
时间自动填充策略
方式一(数据库级别):不推荐使用
在数据库中新建字段并设置为操作的当前时间,且需要在实体类同步属性:
从而达到自动填充时间的。
private Date createTime;
private Date updateTime;
方式二(代码级别):
- 在实体类属性加上对应注解,自动填充时间字段:
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
- 代码逻辑中新建时间对象获取当前时间(推荐使用):
user.setUpdateTime(new Date());
2.4.3乐观锁处理
在面试中经常会提及悲观锁、乐观锁的概念,其实这两个概念非常简单。
乐观锁
乐观锁顾名思义十分乐观,它总是认为不会出现问题,无论干什么都不会去上锁。如果出现问题,就再更新值去测试。
悲观锁
悲观锁顾名思义十分悲观,它总是认为会出现问题,无论干什么都会去上锁,然后再去操作。
乐观锁机制
- 取出记录时,获取当前version
- 更新时带上该version
- 执行更新时,set version = newVersion where version = oldVersion
- 若version不对,则更新失败
乐观锁:1、先去查询获得版本号version = 1
--A线程
update user set name = "zhuzhiqiang",version = version + 1
where id = 2 and version = 1
若B线程抢先完成,这时version = 2,导致线程A修改失败
--B线程
update user set name = "zhuzhiqiang",version = version + 1
where id = 2 and version = 1
测试mybatisPlus的乐观锁插件
1、在数据库表中添加version字段:
2、实体类添加对应属性,并添加@Version注解:
//乐观锁字段(注解)
@Version
private Integer version;
3、注册组件:
@EnableTransactionManagement //事务管理注解
@Configuration
public class MyBatisPlusConfig {
//注册乐观锁插件
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
2.4.4分页查询处理(本质上还是执行limit)
使用步骤
-
配置拦截器组件(配置类中):
//分页查询插件 @Bean public PaginationInterceptor paginationInterceptor(){ return new PaginationInterceptor(); }
-
直接使用Page对象即可:
//测试分页查询 @Test public void testPage(){ //page对象 参数1:当前页;参数2:页面展示条数 Page<User> page = new Page<>(1,5); userMapper.selectPage(page,null); page.getRecords().forEach(System.out::println); }
2.4.5删除操作
逻辑删除
逻辑删除指的是在数据库中没有被删除,而是通过一个变量来使其失效:deleted = 0 -> deleted = 1
-
数据库表中增加字段:
-
实体类中添加对应属性:
//逻辑删除(注解) @TableLogic private Integer deleted;
-
properties配置:
#mybatis-plus逻辑删除配置,删除为1,未删除为0 mybatis-plus.global-config.db-config.logic-delete-value = 1 mybatis-plus.global-config.db-config.logic-not-delete-value = 0
-
测试删除(本质上是一个更新操作):
注:若执行了逻辑删除,那么再次查询该条数据时,会在select语句中自动拼接deleted=0,即查询不到该条语句。
2.4.6条件构造器Wrapper
按照复杂条件进行查询,本质上等价于使用复杂sql进行查询。
-
源码分析:
//wrapper是条件构造器对象,底层继承Wrapper类走SQL查询 QueryWrapper<User> wrapper = new QueryWrapper<>();
-
测试使用:
public void testWrapper(){ String WxUserId = "16"; QueryWrapper<User> wrapper = new QueryWrapper<>(); //相当于where语句,查询一条wx_user_id字段中值为WxUserId,且opinion_id字段中值为opinionId的信息 wrapper .eq("wx_user_id",WxUserId) .eq("opinion_id", opinionId); userMapper.selectOne(wrapper); }
-
复杂条件的SQL查询
-
like模糊查询
public void testLike(){ QueryWrapper<User> wrapper = new QueryWrapper<>(); //相当于where语句, wrapper //表示name字段中 不包含e的数据 .notLike("name","e") //右查询,以t开头的email字段数据 .likeRight("email", "t"); }
-
三、高级用法
3.1基本概念
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
3.2创建工具类
public class AutoCodetool {
public static void main(String[] args) {
//构建代码自动生成器对象
AutoGenerator autoCode = new AutoGenerator();
//全局配置生效
autoCode.setGlobalConfig(gc);
//数据源生效
autoCode.setDataSource(dsc);
//包配置生效
autoCode.setPackageInfo(packageConfig);
//其它策略生效
autoCode.setStrategy(strategyConfig);
//执行代码生成器
autoCode.execute();
}
}
3.3全局配置
//1、全局配置
GlobalConfig gc = new GlobalConfig();
//输出目录,将自动生成的代码生成在以下路径中
String projectPath = System.getProperty("user.dir");
gc.setoutputDir(projectPath + "/src/main/java");
//设置作者信息
gc.setAuthor("Created by zhuzqc");
//生成代码后不打开文件管理器
gc.setopen(false);
//是否覆盖原来生成的代码
gc.setFileOverride(false);
//主键类型
gc.setIdType(IdType.ID_WORKER);
//时间类型
gc.setDateType(DateType.ONLY_DATE);
//配置swagger文档
gc.setSwagger2(true);
3.4设置数据源
//2、设置数据源
DataSourceConfig dsc = new DataSourceConfig();
//数据源具体配置
dsc.setUrl("jdbc:MysqL://localhost:3306/mubatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8");
dsc.setDriverName("com.MysqL.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("password123");
dsc.setDbType(DbType.MysqL);
3.5包的配置
//3、包的配置
PackageConfig packageConfig = new PackageConfig();
//生成包路径
packageConfig.setParent("com.dcone");
//生成模块名
packageConfig.setModuleName("common");
//生成entity
packageConfig.setEntity("pojo");
//生成mapper
packageConfig.setMapper("dao");
//生成service
packageConfig.setService("service");
//生成controller
packageConfig.setController("controller");
3.6其它策略
//4、其它策略
StrategyConfig strategyConfig = new StrategyConfig();
//设置需要映射的数据库表
strategyConfig.setInclude("user");
//驼峰命名
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
//设置Lombok
strategyConfig.setEntityLombokModel(true);
//RESTFUL风格
strategyConfig.setRestControllerStyle(true);
//逻辑删除
strategyConfig.setLogicDeleteFieldName("deleted");
//自动填充配置(创建和修改时间)
TableFill gmtCreate = new TableFill("gmt_create_time", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified_time", FieldFill.INSERT_UPDATE);
autoCode.setStrategy(strategyConfig);
//作为列表元素添加自动填充策略
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategyConfig.setTableFillList(tableFills);
//乐观锁配置
strategyConfig.setVersionFieldName("version");
//访问URL下划线风格
strategyConfig.setControllerMappingHyphenStyle(true);
四、总结
4.1优点
- 通过少量配置即可实现单表大部分 CRUD 操作(将简单查询封装),更有强大的条件构造器,满足各类使用需求;
- 采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎;
- 支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作。
4.2缺点
- 对数据访问层DAO的上层入侵太强,入侵到service、甚至controller,将层次结构耦合起来;
- 数据查询代码复杂,最终sql过程黑盒,不利于业务性优化,不利于排查问题;
- 一旦项目跃迁到微服务,其难以在复杂高性能大规模服务上应用。
Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比
使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。不再需要在Dao中组装查询或更新操作,在xml或mapper中再组装参数。那对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?
需求场景设置
我们通过一个比较典型的业务需求来具体实现和对比下,假如有学生成绩表结构如下:
create table `student_score`
(
id bigint auto_increment comment ''主键ID'' primary key,
student_id bigint not null comment ''学号'',
gender_man tinyint default 0 not null comment ''性别, 0:女; 1:男'',
school_term int null comment ''学期'',
subject varchar(30) null comment ''学科'',
score int null comment ''成绩'',
gmt_create datetime not null comment ''记录创建时间'',
gmt_modified datetime not null comment ''记录最后修改时间'',
is_deleted tinyint default 0 not null comment ''逻辑删除标识''
) engine = InnoDB default charset=utf8;
现在有需求:
统计2000年三门学科(''英语'', ''数学'', ''语文'')及格分数按学期,学科统计最低分,最高分和平均分, 且样本数需要大于1条,统计结果按学期和学科排序
我们可以写SQL语句如下
select school_term,
subject,
count(score) as count,
min(score) as min_score,
max(score) as max_score,
avg(score) as max_score
from student_score
where school_term >= 2000
and subject in (''英语'', ''数学'', ''语文'')
and score >= 60
and is_deleted = 0
group by school_term, subject
having count(score) > 1
order by school_term, subject;
那上面的需求,分别用fluent mybatis, 原生mybatis 和 Mybatis plus来实现一番。
三者实现对比
使用fluent mybatis 来实现上面的功能
我们可以看到fluent api的能力,以及IDE对代码的渲染效果。
换成mybatis原生实现效果
- 定义Mapper接口
public interface MyStudentScoreMapper {
List<Map<String, Object>> summaryScore(SummaryQuery paras);
}
- 定义接口需要用到的参数实体 SummaryQuery
@Data
@Accessors(chain = true)
public class SummaryQuery {
private Integer schoolTerm;
private List<String> subjects;
private Integer score;
private Integer minCount;
}
- 定义实现业务逻辑的mapper xml文件
<select id="summaryScore" resultType="map" parameterType="cn.org.fluent.mybatis.springboot.demo.mapper.SummaryQuery">
select school_term,
subject,
count(score) as count,
min(score) as min_score,
max(score) as max_score,
avg(score) as max_score
from student_score
where school_term >= #{schoolTerm}
and subject in
<foreach collection="subjects" item="item" open="(" close=")" separator=",">
#{item}
</foreach>
and score >= #{score}
and is_deleted = 0
group by school_term, subject
having count(score) > #{minCount}
order by school_term, subject
</select>
- 实现业务接口(这里是测试类, 实际应用中应该对应Dao类)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = QuickStartApplication.class)
public class MybatisDemo {
@Autowired
private MyStudentScoreMapper mapper;
@Test
public void mybatis_demo() {
// 构造查询参数
SummaryQuery paras = new SummaryQuery()
.setSchoolTerm(2000)
.setSubjects(Arrays.asList("英语", "数学", "语文"))
.setScore(60)
.setMinCount(1);
List<Map<String, Object>> summary = mapper.summaryScore(paras);
System.out.println(summary);
}
}
总之,直接使用mybatis,实现步骤还是相当的繁琐,效率太低。那换成mybatis plus的效果怎样呢?
换成mybatis plus实现效果
mybatis plus的实现比mybatis会简单比较多,实现效果如下
如红框圈出的,写mybatis plus实现用到了比较多字符串的硬编码(可以用Entity的get lambda方法部分代替字符串编码)。字符串的硬编码,会给开发同学造成不小的使用门槛,个人觉的主要有2点:
- 字段名称的记忆和敲码困难
- Entity属性跟随数据库字段发生变更后的运行时错误
其他框架,比如TkMybatis在封装和易用性上比mybatis plus要弱,就不再比较了。
生成代码编码比较
fluent mybatis生成代码设置
public class AppEntityGenerator {
static final String url = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";
public static void main(String[] args) {
FileGenerator.build(Abc.class);
}
@Tables(
/** 数据库连接信息 **/
url = url, username = "root", password = "password",
/** Entity类parent package路径 **/
basePack = "cn.org.fluent.mybatis.springboot.demo",
/** Entity代码源目录 **/
srcDir = "spring-boot-demo/src/main/java",
/** Dao代码源目录 **/
daoDir = "spring-boot-demo/src/main/java",
/** 如果表定义记录创建,记录修改,逻辑删除字段 **/
gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted",
/** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/
tables = @Table(value = {"student_score"})
)
static class Abc {
}
}
mybatis plus代码生成设置
public class CodeGenerator {
static String dbUrl = "jdbc:mysql://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8";
@Test
public void generateCode() {
GlobalConfig config = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setDbType(DbType.MYSQL)
.setUrl(dbUrl)
.setUsername("root")
.setPassword("password")
.setDriverName(Driver.class.getName());
StrategyConfig strategyConfig = new StrategyConfig();
strategyConfig
.setCapitalMode(true)
.setEntityLombokModel(false)
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setEntityTableFieldAnnotationEnable(true)
.setFieldPrefix(new String[]{"test_"})
.setInclude(new String[]{"student_score"})
.setLogicDeleteFieldName("is_deleted")
.setTableFillList(Arrays.asList(
new TableFill("gmt_create", FieldFill.INSERT),
new TableFill("gmt_modified", FieldFill.INSERT_UPDATE)));
config
.setActiveRecord(false)
.setIdType(IdType.AUTO)
.setOutputDir(System.getProperty("user.dir") + "/src/main/java/")
.setFileOverride(true);
new AutoGenerator().setGlobalConfig(config)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(
new PackageConfig()
.setParent("com.mp.demo")
.setController("controller")
.setEntity("entity")
).execute();
}
}
FluentMybatis特性一览
三者对比总结
看完3个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。
- | Mybatis Plus | Fluent Mybatis |
---|---|---|
代码生成 | 生成 Entity | 生成Entity, 再通过编译生成 Mapper, Query, Update 和 SqlProvider |
Generator易用性 | 低 | 高 |
和Mybatis的共生关系 | 需替换原有的SqlSessionFactoryBean | 对Mybatis没有任何修改,原来怎么用还是怎么用 |
动态SQL构造方式 | 应用启动时, 根据Entity注解信息构造动态xml片段,注入到Mybatis解析器 | 应用编译时,根据Entity注解,编译生成对应方法的SqlProvider,利用mybatis的Mapper上@InsertProvider @SelectProvider @UpdateProvider注解关联 |
动态SQL结果是否容易DEBUG跟踪 | 不容易debug | 容易,直接定位到SQLProvider方法上,设置断点即可 |
动态SQL构造 | 通过硬编码字段名称, 或者利用Entity的get方法的lambda表达式 | 通过编译手段生成对应的方法名,直接调用方法即可 |
字段变更后的错误发现 | 通过get方法的lambda表达的可以编译发现,通过字段编码的无法编译发现 | 编译时便可发现 |
不同字段动态SQL构造方法 | 通过接口参数方式 | 通过接口名称方式, FluentAPI的编码效率更高 |
语法渲染特点 | 无 | 通过关键变量select, update, set, and, or可以利用IDE语法渲染, 可读性更高 |
Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比
本文主要介绍了Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比,分享给大家,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
目录
三者实现对比
使用fluent mybatis 来实现上面的功能
换成mybatis原生实现效果
换成mybatis plus实现效果
生成代码编码比较
fluent mybatis生成代码设置
mybatis plus代码生成设置
FluentMybatis特性一览
三者对比总结
Fluent Mybatis介绍和源码
使用fluent mybatis可以不用写具体的xml文件,通过java api可以构造出比较复杂的业务sql语句,做到代码逻辑和sql逻辑的合一。
不用再需要在Dao中组装查询或更新操作,在xml或mapper中再组装次参数。
那对比原生Mybatis, Mybatis Plus或者其他框架,FluentMybatis提供了哪些便利呢?
我们通过一个比较典型的业务需求来具体实现和对比下,假如有学生成绩表结构如下:
create table `student_score` ( id bigint auto_increment comment '主键ID' primary key, student_id bigint not null comment '学号', gender_man tinyint default 0 not null comment '性别, 0:女; 1:男', school_term int null comment '学期', subject varchar(30) null comment '学科', score int null comment '成绩', gmt_create datetime not null comment '记录创建时间', gmt_modified datetime not null comment '记录最后修改时间', is_deleted tinyint default 0 not null comment '逻辑删除标识' ) engine = InnoDB default charset=utf8;
现在有需求:
统计2000年三门学科(‘英语', ‘数学', ‘语文')及格分数按学期,学科统计最低分,最高分和平均分,
且样本数需要大于1条,统计结果按学期和学科排序
我们可以写sql语句如下
select school_term, subject, count(score) as count, min(score) as min_score, max(score) as max_score, avg(score) as max_score from student_score where school_term >= 2000 and subject in ('英语', '数学', '语文') and score >= 60 and is_deleted = 0 group by school_term, subject having count(score) > 1 order by school_term, subject;
那上面的需求,分别用fluent mybatis, 原生mybatis 和 Mybatis plus来实现一番。
三者实现对比
使用fluent mybatis 来实现上面的功能
具体代码
我们可以看到fluent api的能力,以及IDE对代码的渲染效果。
换成mybatis原生实现效果
定义Mapper接口
public interface MyStudentscoreMapper { List> summaryscore(SummaryQuery paras); }
定义接口需要用到的参数实体 SummaryQuery
@Data @Accessors(chain = true) public class SummaryQuery { private Integer schoolTerm; private List subjects; private Integer score; private Integer minCount; }
定义实现业务逻辑的mapper xml文件
select school_term, subject, count(score) as count, min(score) as min_score, max(score) as max_score, avg(score) as max_score from student_score where school_term >= #{schoolTerm} and subject in #{item} and score >= #{score} and is_deleted = 0 group by school_term, subject having count(score) > #{minCount} order by school_term, subject
实现业务接口(这里是测试类, 实际应用中应该对应Dao类)
@RunWith(springrunner.class) @SpringBoottest(classes = QuickStartApplication.class) public class MybatisDemo { @Autowired private MyStudentscoreMapper mapper; @Test public void mybatis_demo() { // 构造查询参数 SummaryQuery paras = new SummaryQuery() .setSchoolTerm(2000) .setSubjects(Arrays.asList("英语", "数学", "语文")) .setscore(60) .setMinCount(1); List> summary = mapper.summaryscore(paras); System.out.println(summary); } }
总之,直接使用mybatis,实现步骤还是相当的繁琐,效率太低。
那换成mybatis plus的效果怎样呢?
换成mybatis plus实现效果
mybatis plus的实现比mybatis会简单比较多,实现效果如下
但正如红框圈出的,写mybatis plus实现用到了比较多字符串的硬编码(可以用Entity的get lambda方法部分代替字符串编码)。字符串的硬编码,会给开发同学造成不小的使用门槛,个人觉的主要有2点:
字段名称的记忆和敲码困难
Entity属性跟随数据库字段发生变更后的运行时错误
其他框架,比如TkMybatis在封装和易用性上比mybatis plus要弱,就不再比较了。
生成代码编码比较
fluent mybatis生成代码设置
public class AppEntityGenerator { static final String url = "jdbc:MysqL://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; public static void main(String[] args) { FileGenerator.build(Abc.class); } @Tables( /** 数据库连接信息 **/ url = url, username = "root", password = "password", /** Entity类parent package路径 **/ basePack = "cn.org.fluent.mybatis.springboot.demo", /** Entity代码源目录 **/ srcDir = "spring-boot-demo/src/main/java", /** Dao代码源目录 **/ daoDir = "spring-boot-demo/src/main/java", /** 如果表定义记录创建,记录修改,逻辑删除字段 **/ gmtCreated = "gmt_create", gmtModified = "gmt_modified", logicDeleted = "is_deleted", /** 需要生成文件的表 ( 表名称:对应的Entity名称 ) **/ tables = @Table(value = {"student_score"}) ) static class Abc { } }mybatis plus代码生成设置
public class CodeGenerator { static String dbUrl = "jdbc:MysqL://localhost:3306/fluent_mybatis_demo?useSSL=false&useUnicode=true&characterEncoding=utf-8"; @Test public void generateCode() { GlobalConfig config = new GlobalConfig(); DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MysqL) .setUrl(dbUrl) .setUsername("root") .setPassword("password") .setDriverName(Driver.class.getName()); StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig .setCapitalMode(true) .setEntityLombokModel(false) .setNaming(NamingStrategy.underline_to_camel) .setColumnNaming(NamingStrategy.underline_to_camel) .setEntityTableFieldAnnotationEnable(true) .setFieldPrefix(new String[]{"test_"}) .setInclude(new String[]{"student_score"}) .setLogicDeleteFieldName("is_deleted") .setTableFillList(Arrays.asList( new TableFill("gmt_create", FieldFill.INSERT), new TableFill("gmt_modified", FieldFill.INSERT_UPDATE))); config .setActiveRecord(false) .setIdType(IdType.AUTO) .setoutputDir(System.getProperty("user.dir") + "/src/main/java/") .setFileOverride(true); new AutoGenerator().setGlobalConfig(config) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo( new PackageConfig() .setParent("com.mp.demo") .setController("controller") .setEntity("entity") ).execute(); } }
FluentMybatis特性一览
三者对比总结
看完3个框架对同一个功能点的实现, 各位看官肯定会有自己的判断,笔者这里也总结了一份比较。
-
Mybatis Plus
Fluent Mybatis
代码生成
生成 Entity, Mapper, Wrapper等文件, 并且Generator很好用
只生成Entity, 再通过编译生成 Mapper, Query, Update 和 sqlProvider
和Mybatis的共生关系
需要替换原有的sqlSessionfactorybean
对Mybatis没有任何修改,原来怎么用还是怎么用
动态sql构造方式
应用启动时, 根据Entity注解信息构造动态xml片段,注入到Mybatis解析器
应用编译时,根据Entity注解,编译生成对应方法的sqlProvider,利用mybatis的Mapper上@InsertProvider @SelectProvider @UpdateProvider注解关联
动态sql结果是否容易DEBUG跟踪
不容易debug
容易,直接定位到sqlProvider方法上,设置断点即可
动态sql构造
通过硬编码字段名称, 或者利用Entity的get方法的lambda表达式
通过编译手段生成对应的方法名,直接调用方法即可
字段变更后的错误发现
通过get方法的lambda表达的可以编译发现,通过字段编码的无法编译发现
编译时便可发现
不同字段动态sql构造方法
通过接口参数方式
通过接口名称方式, FluentAPI的编码效率更高
语法渲染特点
无
通过关键变量select, update, set, and, or可以利用IDE语法渲染, 可读性更高
Fluent Mybatis介绍和源码
Fluent Mybatis文档&示例
Fluent Mybatis源码, github
到此这篇关于Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比的文章就介绍到这了,更多相关Fluent Mybatis,原生Mybatis,Mybatis Plus内容请搜索小编以前的文章或继续浏览下面的相关文章希望大家以后多多支持小编!
java-mybaits-015-mybatis逆向工程最佳实践【基础mybatis-generator、tk.mybatis、mubatis-plus】
一、概述
三款框架的功能对比
|
Mybatis-generator |
通用Mapper |
Mybatis-Plus |
代码生成器 |
支持自动生成Model,Mapper,Mapper XML文件 生成方式不够灵活; 生成代码功能较为简单 |
支持自动生成Entity,Mapper,Mapper XML文件; 提供通用的Mapper模板,生成方式较灵活; 生成的Model文件包含注释能够很好地与数据库表完成映射 |
支持自动生成Entity,Mapper,Mapper XML,Service,Controller文件; 提供BaseMapper接口 |
CRUD操作 |
代码生成后每个Mapper有固定的CRUD方法; 在每个Mapper上分别扩展 |
提供通用Mapper接口;方便构造统一service 可以扩展通用接口 |
提供BaseMapper接口; 可以扩展通用接口 |
条件构造器 |
每个实体类自己的Example构造条件【对象方式】 |
提供通用Example【构建sql】 |
提供Wrapper进行复杂条件构造 |
乐观锁 |
|
支持 |
支持 |
主键策略 |
|
支持 |
支持 |
分页 |
|
|
支持 |
逻辑删除 |
|
|
支持 |
通用枚举 |
|
|
支持 |
攻击Sql阻断 |
|
|
支持 |
性能分析 |
|
|
支持 |
通用Mapper是对Mybatis-generator的升级改造,解决了使用Mybatis-generator可能需要大量重构的问题,并且在这个基础上加入了一些新的功能。
Mybatis-Plus可以看作是在另一个方向上对Mybatis的升级改造,不仅能够根据数据库表快速生成pojo实体类,还封装了大量CRUD方法,使用Wrapper解决了复杂条件构造等问题,更是根据开发中常见的问题给出了一系列解决方案。
在拥有Maven和Spring boot的开发框架下,MBG、通用Mapper和MP都可以快速地完成安装,相比于MBG和通用Mapper仅需要执行插件就可以完成基本的开发工作,MP可能需要更多的开发工作量。
最佳实践参看代码:https://github.com/bjlhx15/java_base_architecture.git
二、Mybatis-generator
MyBatis Generator(MBG)是MyBatis MyBatis 和iBATIS的代码生成器。它为所有版本的MyBatis以及版本2.2.0之后的iBATIS版本生成代码。它将根据数据库表生成可用于访问表的文件。
Mybatis-generator主要完成的工作是依据数据库表创建对应的model、dao、mapping文件,可以通过Maven插件或者mybatis-generator的jar包生成。
这里介绍Maven插件使用方法:
1、在pom.xml文件中加入mybatis-generator系列插件;
2、创建generatorConfig.xml文件,在配置文件中指定数据库连接地址、生成类的存放地址、生成对应表的类名等信息;
3、执行mybatis-generator插件,即可生成相应文件;
4、此外,mybatis-generator自动生成了example类用于构造复杂的筛选条件
Mybatis-generator使用较为简单,生成的DAO类及映射文件中包含基本的CRUD操作。
需要注意的是,在一次项目中多次执行mybatis-generator,xml文件会追加,会覆盖原本的Model、DAO;可以使用如下方式
1、每次清理要生成的xml
2、自动生成的写入auto,
3、个人扩展的使用上图方式
可以参看上述github代码
三、通用Mapper【tk.mybatis】
官网:https://github.com/abel533/Mapper/wiki
当数据库字段变化频繁时,使用MBG(mybatis-generator)会带来大量的重构工作,对此,通用Mapper给出的解决办法是:给予开发者一个具备丰富的单表方法并且容易扩展的通用的Mapper。
通用Mapper是对单表的CRUD操作进行了较为详细的实现,使得开发人员可以随意的按照自己的需求选择通用的方法,同时允许开发人员便捷地对通用Mapper进行扩展。
1. 在pom.xml中添加插件配置


<!-- 命令:mvn mybatis-generator:generate -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<!-- 配置实际调用地址-->
<configurationFile>src/main/resources/mybatis_generatorConfig/generatorConfig-base.xml
</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.0.0</version>
</dependency>
</dependencies>
</plugin>
可以看到,通用Mapper的代码生成实际上是使用了MGB,因此通用Mapper的代码生成器只是调用了MGB,然后在这个基础上加入了一些元素来方便开发。
2. 配置文件generatorConfig.xml


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!--导入属性配置,前面我们写的一个配置文件,你也可以直接使用mybatis的jdbc的配置文件 -->
<properties resource="jdbc.properties"></properties>
<!-- 数据库驱动,注意,这里必须要修改成你的数据库的驱动地址 -->
<!-- 如果 pom配置这里可以不写-->
<!-- <classPathEntry location=".m2/repository/mysql/mysql-connector-java/5.1.8/mysql-connector-java-5.1.8.jar"/>-->
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<plugin type="tk.mybatis.mapper.generator.MapperPlugin">
<property name="mappers" value="tk.mybatis.mapper.common.Mapper"/>
<property name="caseSensitive" value="true"/>
</plugin>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}"
userId="${jdbc.username}" password="${jdbc.password}">
</jdbcConnection>
<!-- <javaTypeResolver>-->
<!-- <property name="forceBigDecimals" value="false"/>-->
<!-- </javaTypeResolver>-->
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.github.bjlhx15.mybatis.springboot.base.model.auto"
targetProject="../tk-mybatis-springboot-base1/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper xml 映射文件生成的位置 -->
<sqlMapGenerator targetPackage="autoxml"
targetProject="../tk-mybatis-springboot-base1/src/main/resources/mapper/">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!--targetPackage:mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.github.bjlhx15.mybatis.springboot.base.repository.auto"
targetProject="../tk-mybatis-springboot-base1/src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table tableName="accountbalance" domainObjectName="AccountBalance">
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
</context>
</generatorConfiguration>
与MGB原有的配置文件相比,这里只是多了一个插件的配置,这个插件的作用是:配置生成的Mapper接口都会自动继承这个接口,也就是说,使用通用Mapper生成的mapper接口即使看上去空空如也,但已经具备了大量的对数据库的操作方法。此外,通用 Mapper 专用代码生成器生成的 Model 会在原有基础上增加 @Table,@Id,@Column 等注解,方便自动与数据库字段进行映射。
3. 在 pom.xml 这一级目录的命令行窗口执行 mvn mybatis-generator:generate或者直接在执行mvn插件即可。
4. 通用Mapper同样有Example的设计,与MGB不同的是,MDB会对每一个表生成对应的Example类,而通用Mapper提供了一个统一的Example类,这个类和 MBG 生成的相比,需要自己设置属性名,这个类还额外提供了更多的方法。
通用Mapper可以看作是MGB的改进和扩展,一定程度上解决了使用MGB重构的问题。
可以参看上述github代码
四、Mybatis-Plus
官网地址:https://mp.baomidou.com/guide/generator.html
(以下简称MP)是Mybatis的增强工具(MBG和通用Mapper可看成插件),在Mybatis的基础上增加了很多功能,简化开发,提高效率。
在Spring Boot中的引入:
1. 在maven中添加MP启动器
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.2</version>
</dependency>
2. 要使用代码生成器还需要添加模板引擎依赖
参看地址:AutoGenerator的使用参考 https://mybatis.plus/guide/generator.html 。
添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。
Velocity(默认):
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.1</version>
</dependency>
Freemarker:
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.29</version>
</dependency>
Beetl:
<dependency>
<groupId>com.ibeetl</groupId>
<artifactId>beetl</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
注意!如果您选择了非默认引擎,需要在 AutoGenerator 中 设置模板引擎。


AutoGenerator generator = new AutoGenerator();
// set freemarker engine
generator.setTemplateEngine(new FreemarkerTemplateEngine());
// set beetl engine
generator.setTemplateEngine(new BeetlTemplateEngine());
// set custom engine (reference class is your custom engine class)
generator.setTemplateEngine(new CustomTemplateEngine());
// other config
...
3、代码的自动生成。AutoGenerator是MP的代码生成器,通过调用AutoGenerator,进行相应的模板、策略配置可以快速生成Entity、Mapper、Mapper XML、Service、Controller各个模块的代码。
4. MP将通用的CRUD操作封装进BaseMapper接口,而自动生成的Mapper接口便自动继承了BaseMapper接口。复杂的Sql操作,则可以使用QueryWrapper(LambdaQueryWrapper) 和 UpdateWrapper(LambdaUpdateWrapper)进行动态Sql拼接。
5、此外,MP还支持分页、逻辑删除、通用枚举、Sql注入等功能,在:https://mp.baomidou.com/guide/generator.html
还有性能分析插件:https://mp.baomidou.com/guide/performance-analysis-plugin.html
与MBG不同,使用Mybatis-Plus自动生成代码需要编写代码,通过调用AutoAutoGenerator类实现代码生成,从这方面来说不如使用插件方便。但是它丰富的功能以及只是相对复杂的配置还是使它领先于MBG以及通用Mapper。
双方都
mybatis-plus - MybatisPlusAutoConfiguration
mybatis 的通用maper, 其实有很多, mybatis-plus 算是其中做的比较好的一款了. 这里就来看一下 mybatis-plus 是怎么实现这个通用mapper功能的.
一. BaseMapper
mybatis中 Mapper interface 的时候, 并没有继承什么接口. 所以想要什么方法, 得自己添加.
在mybatis-plus 中, 让 Mapper interface 继承了 BaseMapper 接口, 直接的结果, 就是 Mapper.java 多了很多方法:
public interface BaseMapper<T> {
/**
* <p>
* 插入一条记录
* </p>
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* <p>
* 根据 columnMap 条件,删除记录
* </p>
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* <p>
* 根据 entity 条件,删除记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 删除(根据ID 批量删除)
* </p>
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* <p>
* 根据 ID 修改
* </p>
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* <p>
* 根据 whereEntity 条件,更新记录
* </p>
*
* @param entity 实体对象 (set 条件值,不能为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* <p>
* 查询(根据ID 批量查询)
* </p>
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* <p>
* 查询(根据 columnMap 条件)
* </p>
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* <p>
* 根据 entity 条件,查询一条记录
* </p>
*
* @param queryWrapper 实体对象
*/
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 根据 Wrapper 条件,查询总记录数
* </p>
*
* @param queryWrapper 实体对象
*/
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 根据 entity 条件,查询全部记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 根据 Wrapper 条件,查询全部记录
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 根据 Wrapper 条件,查询全部记录
* 注意: 只返回第一个字段的值
* </p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 根据 entity 条件,查询全部记录(并翻页)
* </p>
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* <p>
* 根据 Wrapper 条件,查询全部记录(并翻页)
* </p>
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
二. MapperScan
MapperScan这块, 还是 mybatis 的功能. 对 Mapper.java 进行扫描注册 : MapperFactoryBean
具体过程见: MapperScan
三. MybatisPlusAutoConfiguration
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean factory = new MybatisSqlSessionFactoryBean();
factory.setDataSource(dataSource);
factory.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation())) {
factory.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
}
applyConfiguration(factory);
if (this.properties.getConfigurationProperties() != null) {
factory.setConfigurationProperties(this.properties.getConfigurationProperties());
}
if (!ObjectUtils.isEmpty(this.interceptors)) {
factory.setPlugins(this.interceptors);
}
if (this.databaseIdProvider != null) {
factory.setDatabaseIdProvider(this.databaseIdProvider);
}
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage())) {
factory.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
}
// TODO 自定义枚举包
if (StringUtils.hasLength(this.properties.getTypeEnumsPackage())) {
factory.setTypeEnumsPackage(this.properties.getTypeEnumsPackage());
}
if (this.properties.getTypeAliasesSuperType() != null) {
factory.setTypeAliasesSuperType(this.properties.getTypeAliasesSuperType());
}
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) {
factory.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
}
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) {
factory.setMapperLocations(this.properties.resolveMapperLocations());
}
// TODO 此处必为非 NULL
GlobalConfig globalConfig = this.properties.getGlobalConfig();
//注入填充器
if (this.applicationContext.getBeanNamesForType(MetaObjectHandler.class,
false, false).length > 0) {
MetaObjectHandler metaObjectHandler = this.applicationContext.getBean(MetaObjectHandler.class);
globalConfig.setMetaObjectHandler(metaObjectHandler);
}
//注入主键生成器
if (this.applicationContext.getBeanNamesForType(IKeyGenerator.class, false,
false).length > 0) {
IKeyGenerator keyGenerator = this.applicationContext.getBean(IKeyGenerator.class);
globalConfig.getDbConfig().setKeyGenerator(keyGenerator);
}
//注入sql注入器
if (this.applicationContext.getBeanNamesForType(ISqlInjector.class, false,
false).length > 0) {
ISqlInjector iSqlInjector = this.applicationContext.getBean(ISqlInjector.class);
globalConfig.setSqlInjector(iSqlInjector);
}
factory.setGlobalConfig(globalConfig);
return factory.getObject();
}
private void applyConfiguration(MybatisSqlSessionFactoryBean factory) {
MybatisConfiguration configuration = this.properties.getConfiguration();
if (configuration == null && !StringUtils.hasText(this.properties.getConfigLocation())) {
configuration = new MybatisConfiguration();
}
if (configuration != null && !CollectionUtils.isEmpty(this.configurationCustomizers)) {
for (ConfigurationCustomizer customizer : this.configurationCustomizers) {
customizer.customize(configuration);
}
}
factory.setConfiguration(configuration);
}
@Bean
@ConditionalOnMissingBean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
ExecutorType executorType = this.properties.getExecutorType();
if (executorType != null) {
return new SqlSessionTemplate(sqlSessionFactory, executorType);
} else {
return new SqlSessionTemplate(sqlSessionFactory);
}
}
关键类对应表:
mybatis | mybatis-plus |
|
|
|
|
|
|
1. MybatisSqlSessionFactoryBean 并不是 SqlSessionFactoryBean 的继承类, 他是一个新类. 其中有很多属性和方法都是从 SqlSessionFactoryBean 中拷贝过来的,然后加了一些东西.
2. MybatisConfiguration 继承自 Configuration 类, 其中加入了一个非常重要的属性:
/**
* Mapper 注册
*/
public final MybatisMapperRegistry mybatisMapperRegistry = new MybatisMapperRegistry(this);
与之对应的是 Configuration 中的:
protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
关于【主流技术】Mybatis Plus的理解与应用和mybatis-plus的作用的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Fluent Mybatis, 原生Mybatis, Mybatis Plus三者功能对比、Fluent Mybatis,原生Mybatis,Mybatis Plus三者功能对比、java-mybaits-015-mybatis逆向工程最佳实践【基础mybatis-generator、tk.mybatis、mubatis-plus】、mybatis-plus - MybatisPlusAutoConfiguration的相关知识,请在本站寻找。
本文标签: