文章目录
前言
官方文档:MyBatis-Plus
一、什么是MybatisPlus
为什么要使用MybatisPlus?MybatisPlus的好处是什么?
因为Mybatis-Plus框架封装了大量CURD的方法,包括我们常用的一些增删改查的SQL命令,Mybatis-Plus都帮我们完成好了,只需要调用相关方法,即可完成对数据库的操作,减少了程序员重复写基本SQL命令的操作,大大提升项目的开发效率。
官网介绍:
MyBatis-Plus是一个MyBatis的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
- 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
- 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
- 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
- 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
- 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
- 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
- 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
- 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
+内置性能分析插件:可输出 SQL 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询 - 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作
二、SpringBoot集成MyBatis-Plus
1.引入相关Maven
<!--mysql数据库驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--mybatis-plus依赖,已经包括了mybatis的依赖了-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!--mybatis-plus的模板引擎依赖,使用mybatyis-plus必须要加这个依赖-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
2.配置数据库
spring:
datasource:
url: jdbc:mysql://localhost:3306/shiyi-blog?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false&allowPublicKeyRetrieval=true
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
#==============================mybatis-plus配置==============================
mybatis-plus:
mapper-locations: classpath:/mapper/*Mapper.xml
#实体扫描,多个package用逗号或者分号分隔
typeAliasesPackage: com.smomo.entity
global-config:
# 数据库相关配置
db-config:
#主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID",ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID";
id-type: AUTO
#字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断"
field-strategy: not_empty
#驼峰下划线转换
column-underline: true
db-type: mysql
#刷新mapper 调试神器
refresh: true
# 原生配置
configuration:
#终端打印SQL执行命令
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
cache-enabled: false
logging:
level: warn
3.使用代码生成器
可以在测试test包下面创建类:
package com.example.mybatisdemo;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
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.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
public class SmomoCode
{
public static void main(String[] args) {
//代码生成器对象
AutoGenerator mpg = new AutoGenerator();
//配置的策略
//1.全局配置
GlobalConfig gc = new GlobalConfig();
//获取当前项目的父路径
String projectPath = System.getProperty("user.dir");
//生成文件夹存放的路径
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("smomo");
gc.setOpen(false);
gc.setFileOverride(false);
gc.setServiceName("%sService");
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
mpg.setGlobalConfig(gc);
//2.设置数据源
DataSourceConfig dataSourceConfig = new DataSourceConfig();
dataSourceConfig.setUrl("jdbc:mysql://localhost:3306/springboot?characterEncoding=UTF-8&useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai&tinyInt1isBit=false&allowPublicKeyRetrieval=true");
dataSourceConfig.setDriverName("com.mysql.cj.jdbc.Driver");
dataSourceConfig.setUsername("root");
dataSourceConfig.setPassword("root");
//设置数据库类型
dataSourceConfig.setDbType(DbType.MYSQL);
mpg.setDataSource(dataSourceConfig);
//3.包的配置
PackageConfig packageConfig = new PackageConfig();
// packageConfig.setModuleName("blog");
packageConfig.setParent("com.example.mybatisdemo");
packageConfig.setEntity("entity");
packageConfig.setMapper("mapper");
packageConfig.setService("service");
packageConfig.setController("controller");
mpg.setPackageInfo(packageConfig);
//策略配置
StrategyConfig strategyConfig = new StrategyConfig();
//添加数据库的表名
strategyConfig.setInclude("user","employee","department");
//去掉表中前缀
// strategyConfig.setTablePrefix("b_");
strategyConfig.setNaming(NamingStrategy.underline_to_camel);
//设置列命名
strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);
strategyConfig.setEntityLombokModel(true);
strategyConfig.setLogicDeleteFieldName("deleted");
//自动填充配置
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified",
FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(gmtCreate);
tableFills.add(gmtModified);
strategyConfig.setTableFillList(tableFills);
//乐观锁
strategyConfig.setVersionFieldName("version");
strategyConfig.setRestControllerStyle(true);
strategyConfig.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategyConfig);
mpg.execute();
}
}
运行main函数
运行成功,生成对应文件。
三、基于Mapper-baseMaper实现CURD方法
- BaseMapper已经封装好通用CURD方法,我们只需要继承BaseMapper,直接调用方法,即可实现基本增删改查操作。如图:
1.插入操作
最终执行的结果,所获取的id为8
这是因为MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id
代码如下:
@Test
public void InserMapper()
{
User user = new User();
user.setName("smomo");
user.setAge(20);
user.setEmail("123");
user.setCreateTime(new Date());
userMapper.insert(user);
System.out.println(user.getId());
}
执行结果:
2.删除操作
删除的执行操作方法4种:
Wrapper的介绍:
Wrapper条件构造器的详细使用
wrapper的具体用法
参数说明:
方法名 | 参数 | 参数说明 |
---|---|---|
delete(@Param(“ew”) Wrapper wrapper) | Wrapper wrapper | Wrapper是条件抽象父类,我们可以使用子类的QueryWrappe和UpdateWrapper来进行条件的构造获取需要的参数。 |
deleteById(Serializable id); | Serializable id | mybatis-plus的底层中Number实现了Serializable接口,所以这里的参数类型可以为任何数字类型。 |
deleteBatchIds(@Param(“coll”) Collection idList) | Collection idList | 参数是collection类型,这里的参数的子类List、Set、Queue类型 |
deleteByMap(@Param(“cm”) Map<String, Object> columnMap) | Map<String, Object> columnMap | 参数类型的Map集合,这里可以是参数类型子类HashMap、Hashtable、concurrentHashMap、TreeMap、 IdentityHashMap ,LinkedHashMap。 |
baseMapper.delete()
@Test
public void DeleteMapper()
{
//QueryWrapper的构造条件进行删除,这里的意思查询name为smomo的进行删除
int delete = userMapper.delete(new QueryWrapper<User>().eq("name", "smomo"));
}
执行结果:
baseMapper.deleteById()
@Test
public void DeleteMapper()
{
//根据主键id进行删除
int user = userMapper.deleteById(9);
}
执行结果:
baseMapper.deleteBatchIds()
代码如下:
@Test
public void DeleteMapper()
{
ArrayList<Integer> list = new ArrayList<>();
list.add(6);
//这里是根据集合的id进行删除
int user = userMapper.deleteBatchIds(list);
}
执行结果:
baseMapper.deleteByMap()
代码如下:
@Test
public void DeleteMapper()
{
Map<String, Object> map = new HashMap<>();
map.put("name","xiaoming");
map.put("age",21);
int user = userMapper.deleteByMap(map);
}
执行结果如下:
3.更新操作
更新信息的操作方法有两种:
参数说明:
方法名 | 参数 | 参数说明 |
---|---|---|
update( T entity, Wrapper updateWrapper) | T entity;Wrapper updateWrapper | 这里需要的参数有两个,T entity 指是实体类,updateWrapper指的是条件构造器 |
updateById(@Param(“et”) T entity); | T entity | T entity指的是实体类,这里注意实体类id不能空,否则不能完成信息的更改。 |
baseMapper.update()
代码如下:
@Test
public void UpdateMapper()
{
User user = new User();
user.setAge(50);
//这里的查询name="super",更新年龄为50,有条件构造器参数,好处是可以批量操作。
int update = userMapper.update(user, new UpdateWrapper<User>().eq("name", "super"));
}
执行结果如下:
### baseMapper.updateById()
注意,实体类的id不能为空
代码如下:
@Test
public void UpdateMapper2()
{
User user = new User();
user.setId(12L);
user.setName("luck");
int i = userMapper.updateById(user);
}
执行结果如下:
4.查询操作
查询的操作方法有10种:
每个方法里的参数类型,这次不详细介绍,可参考上面的类型说明。
baseMapper.selectById()
说明:根据主键id查询信息
代码如下:
@Test
public void SelectMapper()
{
User user = userMapper.selectById(1);
}
执行结果如下:
baseMapper.selectBatchIds()
说明:批量操作,根据集合里多个id查询所有id的全部信息
代码如下:
@Test
public void SelectMappe2()
{
List<Integer> Idslist = new ArrayList<>();
Idslist.add(1);
Idslist.add(2);
Idslist.add(3);
userMapper.selectBatchIds(Idslist);
}
执行结果如下:
baseMapper.selectOne()
说明:查询某个对象的信息,根据条件构造器构造的特殊条件
@Test
public void SelectMappe3()
{
User info = userMapper.selectOne(new QueryWrapper<User>().eq("name", "Sandy"));
}
执行结果如下:
baseMapper.selectByMap()
说明:批量操作,Map作为条件参数查询所有信息
代码如下:
@Test
public void SelectMappe4()
{
Map<String, Object> map = new HashMap<>();
map.put("age",18);
List<User> users = userMapper.selectByMap(map);
}
执行结果:
baseMapper.selectMaps()
根据条件构造器进行查询,返回值得List<Map<String, Object>>
代码如下:
@Test
public void SelectMappe5()
{
List<Map<String, Object>> list = userMapper.selectMaps(new QueryWrapper<User>().eq("age", 18));
}
执行结果:
baseMapper.selectList()
根据条件构造器进行查询,返回值得List<T>
代码如下:
@Test
public void SelectMappe6()
{
List<User> list = userMapper.selectList(new QueryWrapper<User>().eq("age", 18));
}
执行结果:
userMapper.selectCount()
查询数据库的数量
@Test
public void SelectMappe7()
{
//根据条件查询数据的条数,null代表查询全部
Integer count = userMapper.selectCount(null);
System.out.println(count);
}
执行结果如下:
baseMapper.selectObjs()
根据条件查询数据的条数,返回值是List<object>
@Test
public void SelectMappe8()
{
//根据条件查询数据的条数,返回值是List<object>
List<Object> list = userMapper.selectObjs(new QueryWrapper<User>().eq("age",20));
System.out.println(list);
}
5.分页查询
Page对象
该类继承了 IPage 类,实现了 简单分页模型 如果你要实现自己的分页模型可以继承 Page 类或者实现 IPage 类
baseMapper.selectPage()
分页查询数据,返回值为 Page<T>
@Test
public void SelectMappe10()
{
Page<User> page = new Page<>(1,5);
Page<User> list = userMapper.selectPage(page, null);
List<User> records = list.getRecords();
records.forEach(System.out::println);
System.out.println(list.getCurrent());
}
执行结果:
baseMapper.selectMapsPage()
可以进行构造的条件分页查询数据,返回值 Page<Map<String, Object>>
@Test
public void SelectMappe7()
{
Page<Map<String, Object>> page = new Page<>(1, 3);
Page<Map<String, Object>> pageParam = userMapper.selectMapsPage(page, null);
List<Map<String, Object>> records = pageParam.getRecords();
//读取每个对象的信息
records.forEach(System.out::println);
//获取当前页
System.out.println(pageParam.getCurrent());
System.out.println(pageParam.getPages());
System.out.println(pageParam.getSize());
System.out.println(pageParam.getTotal());
System.out.println(pageParam.hasNext());
System.out.println(pageParam.hasPrevious());
}
执行结果: