文章目录
MyBatisPlus
快速入门
1.简介
MyBatis-Plus
(简称MP
)是一个MyBatis
的增强工具,在MyBatis
基础上只做增强不做改变,为简化开发,提高效率而生
2.特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
3.支持数据库
任何能使用
MyBatis
进行 CRUD, 并且支持标准 SQL 的数据库,具体支持情况如下,如果不在下列表查看分页部分教程 PR 您的支持。
- MySQL,Oracle,DB2,H2,HSQL,SQLite,PostgreSQL,SQLServer,Phoenix,Gauss ,ClickHouse,Sybase,OceanBase,Firebird,Cubrid,Goldilocks,csiidb
- 达梦数据库,虚谷数据库,人大金仓数据库,南大通用(华库)数据库,南大通用数据库,神通数据库,瀚高数据库
4.框架结构
执行的流程是:通过BaseMapper
扫描POJO
实体类,通过反射分析表的字段,再分析调用的方法是增删还是改查,最终通过反射Mapper
将生成实现类放到MyBatis
容器中
快速入门
1.创建数据库及表
创建表:
#mybatis_plus
CREATE DATABASE `mybatis_plus` /*!40100 DEFAULT CHARACTER SET utf8mb4 */;
USE `mybatis_plus`;
CREATE TABLE `user` (
`id` BIGINT(20) NOT NULL COMMENT '主键ID',
`name` VARCHAR(30) DEFAULT NULL COMMENT '姓名',
`age` INT(11) DEFAULT NULL COMMENT '年龄',
`email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
注意是:由于mybatis_plus
使用雪花算法
,在主键
自动生成时会很长,所以需要使用BIGINTG
数据类型
插入数据:
INSERT INTO USER (id, NAME, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
2.创建一个SpringBoot
工程
注意是:由于在创建工程时,我们还没有添加mybatis_plus
的场景启动器,所以下面需要我们手动添加
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
3.配置application.yml
信息
建议直接复制修改,防止写错
#修改端口号
server:
port: 80
spring:
#配置数据源信息
datasource:
#配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
username: root
password: root
注意
1、驱动类driver-class-name
spring boot 2.0(内置jdbc5驱动),驱动类使用:
driver-class-name: com.mysql.jdbc.Driver
spring boot 2.1及以上(内置jdbc8驱动),驱动类使用:
driver-class-name: com.mysql.cj.jdbc.Driver
否则运行测试用例的时候会有 WARN 信息
2、连接地址url
MySQL5.7版本的url:
jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&useSSL=false
MySQL8.0版本的url:
jdbc:mysql://localhost:3306/mybatis_plus?
serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
否则运行测试用例报告如下错误:
java.sql.SQLException: The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or
represents more
4.创建POJO
实体类
由于mybatis
是ORM
框架,表示表和对象的映射关系
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
// 注意是:由于在表中使用的bigint类型,所以需要使用long类型
private Long id;
private String name;
private Integer age;
private String email;
}
5.创建Mapper
接口并继承BaseMapper
接口
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
注意是:也可以在springboot
启动类中,添加@MapperSacn
扫描包的方式,但是不建议
@SpringBootApplication
// 扫描mapper接口所在的包
@MapperScan("com.haikang.plus.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class, args);
}
}
6.编写测试方法
@SpringBootTest
public class MyBatisPlusTest {
// 注入UserMapper对象
@Autowired
public UserMapper userMapper;
@Test
void selectAllUser(){
// selectList需要传入条件,传入null表示查询全部
List<User> users = userMapper.selectList(null);
users.forEach(user -> System.out.println(user));
}
}
7.添加日志功能
mybatis-plus:
configuration:
#mybatisplus日志配置
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
BseaMapper
源码分析
1.根据条件查询返回List
集合
源码:
selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper)
方法
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
测试
@Test
void selectAllUser(){
// selectList需要传入条件,传入null表示查询全部
List<User> users = userMapper.selectList(null);
users.forEach(user -> System.out.println(user));
}
2.插入功能
源码:
insert
方法
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
测试
// 插入数据
@Test
void insert(){
User user = new User(null,"明天",21,"123@qq.com");
int insert = userMapper.insert(user);
System.out.println("result:"+insert);
System.out.println("id:"+user.getId());
}
3.删除功能
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据实体(ID)删除
*
* @param entity 实体对象
* @since 3.4.4
*/
int deleteById(T entity);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 删除(根据ID或实体 批量删除)
*
* @param idList 主键ID列表或实体列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<?> idList);
测试:
// 删除功能
@Test
void delete(){
// 根据ID进行删除
// DELETE FROM user WHERE id=?
int id = userMapper.deleteById(6);
System.out.println(id);
// 根据实体ID删除
// DELETE FROM user WHERE id=?
long l = 23L;
User user = new User(l,"6",6,"6");
int userId = userMapper.deleteById(user);
System.out.println(userId);
// 根据collection集合批量删除
// DELETE FROM user WHERE id IN ( ? , ? , ? , ? )
List<Integer> listId = Arrays.asList(7,8,9,10);
int batchIds = userMapper.deleteBatchIds(listId);
System.out.println(batchIds);
// 根据Map集合封装数据进行删除
// DELETE FROM user WHERE name = ? AND age = ? AND email = ?
Map<String,Object> map = new HashMap<>();
map.put("name","海康");
map.put("age",21);
map.put("email","123@qq.com");
int deleteByMap = userMapper.deleteByMap(map);
System.out.println(deleteByMap);
}
4.修改功能
源码:
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
测试:
// 测试功能
@Test
void update(){
User user = new User();
user.setId(8l);
user.setName("海康");
user.setAge(23);
user.setEmail("123@qq.com");
// UPDATE user SET name=?, age=?, email=? WHERE id=?
int update = userMapper.updateById(user);
System.out.println(update);
}
5.查询功能
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
* <p>查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
List<T> ts = this.selectList(queryWrapper);
if (CollectionUtils.isNotEmpty(ts)) {
if (ts.size() != 1) {
throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
}
return ts.get(0);
}
return null;
}
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Long selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
测试
// 查询功能
@Test
void select(){
// 根据ID查询用户信息
// SELECT id,name,age,email FROM user WHERE id=?
User user = userMapper.selectById(1l);
System.out.println(user);
// 根据Map集合封装条件查询
// SELECT id,name,age,email FROM user WHERE name = ? AND age = ? AND email = ?
Map<String,Object> map = new HashMap<>();
map.put("name","明天");
map.put("age",21);
map.put("email","123@qq.com");
List<User> users = userMapper.selectByMap(map);
System.out.println(users);
// 根据多个ID查询多条数据
// SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
List<Long> asList = Arrays.asList(1l, 2l, 3l );
List<User> selectBatchIds = userMapper.selectBatchIds(asList);
selectBatchIds.forEach(user1 -> System.out.println(user1));
// 根据条件进行查询返回List集合,如果没有传入条件(null),表示查询全部
// SELECT id,name,age,email FROM user
List<User> selectList = userMapper.selectList(null);
selectList.forEach(user2-> System.out.println(user2));
// 查询总记录数,如果没有传入条件(null),表示查询所有记录数
// SELECT COUNT( * ) FROM user
Long aLong = userMapper.selectCount(null);
System.out.println(aLong);
}
通过观察BaseMapper中的方法,大多方法中都有Wrapper类型的形参,此为条件构造器,可针 对于SQL语句设置不同的条件,若没有条件,则可以为该形参赋值null,即查询(删除/修改)所 有数据
6.自定义功能
例如:我们可以查看返回Map
集合,用于JSON
数据返回
第一步:在UserMapper
接口定义方法
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 自定义返回Map集合功能
// 根据Id查询
@MapKey("id")
Map<String,Object> getUserById(@Param("id")Long id);
}
第二步:定义UserMapper.xml
文件
<mapper namespace="com.haikang.plus.mapper.UserMapper">
<!--
// 自定义返回Map集合功能
// 根据Id查询
Map<String,Object> getUserById(@Param("id")Long id);
-->
<select id="getUserById" resultType="map">
select * from user where id=#{id};
</select>
</mapper>
第三步:在核心配置文件
中指定maper.xml
文件的位置
mybatis-plus:
configuration:
#mybatisplus日志配置
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
#指定xml的位置
mapper-locations: /mapper/**/**.xml #也是默认位置
mybatis-plus
默认位置是:
第四步:编写控制器测试
// 自定义功能
@Test
void map(){
// 根据ID查询用户信息,并且返回Map方式
// select * from user where id=?;
Map<String, Object> map = userMapper.getUserById(1l);
System.out.println(map);
// 返回值:{name=Jone, id=1, age=18, email=test1@baomidou.com}
}
BaseMapper
源码
/**
* Mapper 继承该接口后,无需编写 mapper.xml 文件,即可获得CRUD功能
* <p>这个 Mapper 支持 id 泛型</p>
*
* @author hubin
* @since 2016-01-23
*/
public interface BaseMapper<T> extends Mapper<T> {
/**
* 插入一条记录
*
* @param entity 实体对象
*/
int insert(T entity);
/**
* 根据 ID 删除
*
* @param id 主键ID
*/
int deleteById(Serializable id);
/**
* 根据实体(ID)删除
*
* @param entity 实体对象
* @since 3.4.4
*/
int deleteById(T entity);
/**
* 根据 columnMap 条件,删除记录
*
* @param columnMap 表字段 map 对象
*/
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,删除记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 删除(根据ID或实体 批量删除)
*
* @param idList 主键ID列表或实体列表(不能为 null 以及 empty)
*/
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<?> idList);
/**
* 根据 ID 修改
*
* @param entity 实体对象
*/
int updateById(@Param(Constants.ENTITY) T entity);
/**
* 根据 whereEntity 条件,更新记录
*
* @param entity 实体对象 (set 条件值,可以为 null)
* @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
*/
int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);
/**
* 根据 ID 查询
*
* @param id 主键ID
*/
T selectById(Serializable id);
/**
* 查询(根据ID 批量查询)
*
* @param idList 主键ID列表(不能为 null 以及 empty)
*/
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
/**
* 查询(根据 columnMap 条件)
*
* @param columnMap 表字段 map 对象
*/
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
/**
* 根据 entity 条件,查询一条记录
* <p>查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
default T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper) {
List<T> ts = this.selectList(queryWrapper);
if (CollectionUtils.isNotEmpty(ts)) {
if (ts.size() != 1) {
throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records");
}
return ts.get(0);
}
return null;
}
/**
* 根据 Wrapper 条件,判断是否存在记录
*
* @param queryWrapper 实体对象封装操作类
* @return
*/
default boolean exists(Wrapper<T> queryWrapper) {
Long count = this.selectCount(queryWrapper);
return null != count && count > 0;
}
/**
* 根据 Wrapper 条件,查询总记录数
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
Long selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录
* <p>注意: 只返回第一个字段的值</p>
*
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 entity 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件(可以为 RowBounds.DEFAULT)
* @param queryWrapper 实体对象封装操作类(可以为 null)
*/
<P extends IPage<T>> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
/**
* 根据 Wrapper 条件,查询全部记录(并翻页)
*
* @param page 分页查询条件
* @param queryWrapper 实体对象封装操作类
*/
<P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}
通用Service
1.Service
接口CRUD
说明:
- 通用 Service CRUD 封装[IService (opens new window)])接口,进一步封装 CRUD 采用
get 查询单行
remove 删除
list 查询集合
page 分页
前缀命名方式区分Mapper
层避免混淆,- 泛型
T
为任意实体对象- 建议如果存在自定义通用 Service 方法的可能,请创建自己的
IBaseService
继承Mybatis-Plus
提供的基类- 对象
Wrapper
为 [条件构造器])
A.IService
接口
MyBatis-plus
中有一个接口IService
和其实现类ServiceImpl
,封装了常见业务层逻辑详情查看源码IService
和SerivceImpl
所以我们可以自定义Serivce
接口和实现类,继承和实现相关的接口和类
第一步:定义UserSerivce
继承Iservice
接口
/**
* UserService继承IService模板提供的基础功能
*/
public interface UserService extends IService<User> {
}
第二步:定义UserServiceImpl
实现类
/**
* ServiceImpl实现了IService,提供了IService中基础功能的实现
* 若ServiceImpl无法满足业务需求,则可以使用自定的UserService定义方法,并在实现类中实现
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
第三步:编写测试类
@SpringBootTest
public class MyBatisPlusServiceTest {
@Autowired
UserService userService;
// 查询总记录数
@Test
void count(){
// SELECT COUNT( * ) FROM user;
long count = userService.count();
System.out.println(count);
}
// 保存数据
@Test
void save(){
// 保存一条记录
// INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
boolean save = userService.save(new User(9l, "湛江", 21, "123@qq.com"));
System.out.println(save);
// 批量保存多条数据
// INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
List<User> asList = Arrays.asList(new User(10l, "西安", 22, "123qq.com"),
new User(11l, "南宁", 22, "123qq.com"),
new User(12l, "新疆", 23, "123qq.com"));
boolean batch = userService.saveBatch(asList);
System.out.println(batch);
}
// 修改数据
@Test
void update(){
// 修改一条数据
// UPDATE user SET name=?, age=?, email=? WHERE id=?
boolean update = userService.updateById(new User(12l, "新疆", 20, "123@qq.com"));
System.out.println(update);
}
// 删除操作
@Test
void remove(){
// DELETE FROM user WHERE id=?
// 根据Id删除
boolean remove = userService.removeById(12l);
System.out.println(remove);
}
}
这两个方法即有添加也有修改的功能,在没有Id
时,表示添加,有Id
时,表示修改
`public boolean saveOrUpdate(T entity)`
`public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize)`
更多操作请求参照官方文档 CRUD 接口 | MyBatis-Plus (baomidou.com)
ServiceImpl
源码
/**
* IService 实现类( 泛型:M 是 mapper 对象,T 是实体 )
*
* @author hubin
* @since 2018-06-23
*/
@SuppressWarnings("unchecked")
public class ServiceImpl<M extends BaseMapper<T>,