一、入门案例
原理:扫描实体类—通过反射抽取属性—对应分析操作的表和字段—生成相对应SQL语句—注入到mybatis容器中
创建好数据库及表
1. 创建SpringBoot项目,引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. 配置application.yml
spring:
# 配置数据源信息
datasource:
# 配置数据源类型
type: com.zaxxer.hikari.HikariDataSource
# 配置连接数据库的各个信息
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
username: root
password: 123456
# 配置MyBatis日志
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 配置类型别名对应的包
type-aliases-package: com.zju.mybatisplus.pojo
3. 添加实体类
//@Data相当于getter+setter+toString+equals+hashcode+toString+无参构造
@Data
public class User {
//对应表中BigInt类型
private Long id;
private String name;
private Integer age;
private String email;
}
4. 启动类
在SpringBoot启动类中添加@MapperScan注解,扫描mapper包
@MapperScan("com.zju.mybatisplus.mapper")
@SpringBootApplication
public class MybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisplusApplication.class, args);
}
}
5. 添加mapper
BaseMapper是MyBatis-Plus提供的模板mapper,其中包含了基本的CRUD方法,泛型为操作的实体类型
扫描mapper所在的包后,将动态生成的代理实现类交给IOC容器管理,IDEA匹配不到,可以加上@Repository
@Repository
public interface UserMapper extends BaseMapper<User> {
}
6. 测试
@SpringBootTest
public class MybatisPlusTest {
@Autowired
UserMapper userMapper;
@Test
public void testSelectList(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}
注意:
IDEA在 userMapper 处报错,因为找不到注入的对象,因为类是动态创建的,但是程序可以正确的执行。
为了避免报错,可以在mapper接口上添加 @Repository 注解
二、基本CURD
MyBatis-Plus中的基本CRUD在内置的BaseMapper中都已得到了实现,我们可以直接使用,insert,delete,update,select开头
1. 插入
User user = new User(null, "张三", 23, "zhangsan@atguigu.com");
//INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
int result = userMapper.insert(user);
最终执行的结果,所获取的id为1475754982694199298
这是因为MyBatis-Plus在实现插入数据时,会默认基于雪花算法的策略生成id
2. 删除
a> 通过id删除记录
//DELETE FROM user WHERE id=?
userMapper.deleteById(1475754982694199298L);
b> 通过id批量删除记录
//DELETE FROM user WHERE id IN ( ? , ? , ? )
List<Long> idList = Arrays.asList(1L, 2L, 3L);
int result = userMapper.deleteBatchIds(idList);
c> 通过map条件删除记录
//根据map集合中所设置的条件删除记录
//DELETE FROM user WHERE name = ? AND age = ?
Map<String, Object> map = new HashMap<>();
map.put("age", 23);
map.put("name", "张三");
int result = userMapper.deleteByMap(map);
3. 修改
User user = new User(1523942622517624833L,"fkd",23,"fkd@163.com");
//UPDATE user SET name=?, age=?, email=? WHERE id=?
userMapper.updateById(user);
4. 查询
a> 根据id查询用户信息
//根据id查询用户信息
//SELECT id,name,age,email FROM user WHERE id=?
User user = userMapper.selectById(4L);
b> 根据多个id查询多个用户信息
//根据多个id查询多个用户信息
//SELECT id,name,age,email FROM user WHERE id IN ( ? , ? )
List<Long> idList = Arrays.asList(1L, 2L, 3L);
List<User> list = userMapper.selectBatchIds(idList);
c> 通过map条件查询用户信息
//通过map条件查询用户信息
//SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
Map<String, Object> map = new HashMap<>();
map.put("age", 23);
map.put("name", "fkd");
List<User> list = userMapper.selectByMap(map);
list.forEach(System.out::println);
d> 查询所有数据
//查询所有用户信息
//SELECT id,name,age,email FROM user
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
5. 自定义功能
- 默认映射文件路径:classpath*:/mapper/**/xxx.xml
mybatis-plus:
mapper-locations: /mapper/*.xml
- 在UserMapper接口中添加方法
@Repository
public interface UserMapper extends BaseMapper<User> {
/**
* 根据ID查询用户信息为map集合
* @param id
* @return
*/
Map<String, Object> selectMapById(@Param("id") Long id);
}
- UserMapper.xml中写对应xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zju.mybatisplus.mapper.UserMapper">
<!--Map<String, Object> selectMapById(Long id)-->
<select id="selectMapById" resultType="map">
select id,name,age,email from user where id=#{id}
</select>
</mapper>
6. 通用service
- 通用 Service CRUD 封装
IService
接口,进一步封装 CRUD 采用save
保存、update
更新、get
查询单行、remove
删除、list
查询集合、page
分页 前缀命名方式区分 Mapper 层避免混淆- Iservice接口,ServiceImpl实现类
- saveOrUpdate()方法中实体类对象有ID是修改,没有ID是添加
- 创建service接口
/
**
* UserService继承IService模板提供的基础功能
*/
public interface UserService extends IService<User> {
}
- 创建对应实现类
/**
* ServiceImpl实现了IService,提供了IService中基础功能的实现
* 若ServiceImpl无法满足业务需求,则可以使用自定的UserService定义方法,并在实现类中实现
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
a >测试查询总记录数
//ELECT COUNT( * ) FROM user
long count = userService.count();
**b> 测试批量插入 **
@Test
public void testSaveBatch(){
// SQL长度有限制,海量数据插入单条SQL无法实行
// 因此MP将批量插入放在了通用Service中实现,而不是通用Mapper
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setName("ybc" + i);
user.setAge(20 + i);
users.add(user);
}
//SQL:INSERT INTO t_user (username, age) VALUES ( ?, ? )
userService.saveBatch(users);
}
三、常用注解
MyBatis-Plus在确定操作的表时,由BaseMapper的泛型决定,即实体类型决
定,且默认操作的表名和实体类型的类名一致
1. @TableName
在实体类类型上添加@TableName(“t_user”),标识实体类对应的表。解决表名与实体类不对应的问题
@TableName("t_user")
@AllArgsConstructor
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
- 全局配置,指定所有实体类对应表有一个指定前缀t_
mybatis-plus:
global-config:
db-config:
# 配置MyBatis-Plus操作表的默认前缀
table-prefix: t_
2. @TableId
MybatisPlus默认将id作为主键列,并在插入数据时,默认基于雪花算法的策略生成id
问题:当主键名为uid等非id字段时不会默认赋值
- @TableId的value属性
@TableId(value="uid")
private Long id;
- @TableId的type属性
@TableId(value = "id",type= IdType.AUTO)
private Long id;
2.1 配置全局主键策略
mybatis-plus:
configuration:
# 配置MyBatis日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 配置MyBatis-Plus操作表的默认前缀
table-prefix: t_
# 配置MyBatis-Plus的主键策略
id-type: auto
自增策略可以不指定id
2.2 雪花算法
需要选择合适的方案去应对数据规模的增长,以应对逐渐增长的访问压力和数据量
数据库的扩展方式主要包括:业务分库、主从复制,数据库分表
- 主从复制:主从服务器内容一致,主服务器写,从服务器读,读写分离
- 数据库分表
同一业务的单表数据也会达到单台数据库服务器的处理瓶颈,对单表进行拆分:垂直分表和水平分表
-
水平分表
- 主键自增:可以随着数据的增加平滑地扩充新的表,但分布不均匀
- 取模:表分布比较均匀,但扩充新的表很麻烦,所有数据都要重分布
-
雪花算法
雪花算法是由Twitter公布的分布式主键生成算法,它能够保证不同表的主键的不重复性,以及相同表的主键的有序性。
64位,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高
3. @TableField
解决实体类中的属性名和字段名不一致的情况
- MyBatis-Plus会自动将下划线命名风格转化为驼峰命名风格
- 若实体类中的属性和表中的字段不满足情况驼峰对应
@TableField("user_name")
private String name;
4. @TableLogic
- 物理删除:真实删除,将对应数据从数据库中删除,之后查询不到此条被删除的数据
- 逻辑删除:假删除,将对应数据中代表是否被删除字段的状态修改为“被删除状态”,之后在数据库中仍旧能看到此条数据记录
- 使用场景:可以进行数据恢复
实现逻辑删除:
step1: 数据库中创建逻辑删除状态列,设置默认值为0
step2: 实体类中添加逻辑删除属性
@TableLogic
private Integer isDeleted;
测试,此时删除只会将isDeleted置为1
-
测试删除功能,真正执行的是修改
UPDATE t_user SET is_deleted=1 WHERE id=? AND is_deleted=0
-
测试查询功能,被逻辑删除的数据默认不会被查询
SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0
四、条件构造器和常用接口
1. QueryWrapper
delete和select都是where筛选的,默认链式连接是AND,.or()改变为or
- 组装查询条件
查询用户名包含a,年龄在20到30之间,并且邮箱不为null的用户信息
@Test
public void testSelect(){
QueryWrapper<User> queryWrapper =new QueryWrapper<>();
/*SELECT id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 AND
(user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)*/
queryWrapper.like("user_name", "a")
.between("age", 20, 30)
.isNotNull("email");
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
- 组装排序条件
按年龄降序查询用户,如果年龄相同则按id升序排列
@Test
public void test02(){
//按年龄降序查询用户,如果年龄相同则按id升序排列
//SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0 ORDER BY age DESC,id ASC
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper
.orderByDesc("age")
.orderByAsc("id");
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
- 组装删除条件
删除email为空的用户
@Test
public void test03(){
//删除email为空的用户
//DELETE FROM t_user WHERE (email IS NULL)
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.isNull("email");
//条件构造器也可以构建删除语句的条件
int result = userMapper.delete(queryWrapper);
System.out.println("受影响的行数:" + result);
}
- 实现修改功能
将(年龄大于20并且用户名中包含有a)或邮箱为null的用户信息修改
@Test
public void test04() {
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//UPDATE t_user SET age=?, email=? WHERE is_deleted=0 AND (user_name LIKE ? AND age > ? OR email IS NULL)
queryWrapper
.like("username", "a")
.gt("age", 20)
.or()
.isNull("email");
User user = new User();
user.setAge(18);
user.setEmail("user@atguigu.com");
int result = userMapper.update(user, queryWrapper);
System.out.println("受影响的行数:" + result);
}
将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
lambda表达式内的逻辑优先运算
@Test
public void testSelect(){
//将用户名中包含有a并且(年龄大于20或邮箱为null)的用户信息修改
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//UPDATE t_user SET age=?, email=? WHERE is_deleted=0 AND (user_name LIKE ? AND (age > ? OR email IS NULL))
queryWrapper.like("user_name", "a")
.and(i -> i.gt("age", 20).or().isNull("email"));
User user = new User();
user.setEmail("fkdwz@qq.com");
user.setAge(28);
int result = userMapper.update(user, queryWrapper);
System.out.println(result);
}
}
- **组装select子句(查询字段) **
查询年龄大于23岁的用户信息的username和age字段
selectMaps()返回Map集合列表,通常配合select()使用,避免User对象中没有被查询到的列值为null
@Test
public void testSelect(){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.select("user_name","age").gt("age",23);
List<Map<String, Object>> list = userMapper.selectMaps(queryWrapper);
list.forEach(System.out::println);
}
- 实现子查询
查询id小于等于3的用户信息
@Test
public void test06() {
//SELECT id,username AS name,age,email,is_deleted FROM t_user WHERE (id IN (select id from t_user where id <= 3))
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.inSql("id", "select id from t_user where id <= 3");
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
2. UpdateWrapper
UpdateWrapper省略了QueryWrapper中创建实体类的操作
有两个功能:设置修改字段,设置修改条件
将(年龄大于20或邮箱为null)并且用户名中包含有i的用户信息修改
@Test
public void testSelect(){
//将(年龄大于20或邮箱为null)并且用户名中包含有i的用户信息修改
UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//UPDATE t_user SET user_name=?,age=? WHERE is_deleted=0 AND ((age > ? OR email IS NULL) AND user_name LIKE ?)
updateWrapper.set("user_name", "wz").set("age",24)
.and(i-> i.gt("age",20).or().isNull("email"))
.like("user_name","i");
userMapper.update(null, updateWrapper);
}
3. condition
根据条件组装SQL
@Test
public void testSelect(){
//根据用户名模糊查询并且根据年龄区间查询
String username = "w";
Integer beginAge = 20;
Integer endAge = 30;
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//StringUtils.isNotBlank()判断某字符串是否不为null且长度不为0且不由空白符(whitespace)构成
queryWrapper.like(StringUtils.isNotBlank(username),"user_name", username)
.gt(beginAge != null, "age", beginAge)
.lt(endAge != null, "age", endAge);
List<User> list = userMapper.selectList(queryWrapper);
list.forEach(System.out::println);
}
4. LamdaXXXWrapper
用函数式接口访问某一个属性对应的字段,防止运行时错误
- LamdaQueryWrapper
@Test
public void test09() {
//定义查询条件,有可能为null(用户未输入)
String username = "a";
Integer ageBegin = 10;
Integer ageEnd = 24;
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//避免使用字符串表示字段,防止运行时错误
queryWrapper
.like(StringUtils.isNotBlank(username), User::getName, username)
.ge(ageBegin != null, User::getAge, ageBegin)
.le(ageEnd != null, User::getAge, ageEnd);
List<User> users = userMapper.selectList(queryWrapper);
users.forEach(System.out::println);
}
- LamdaUpdateWrapper
@Test
public void test10() {
//组装set子句
LambdaUpdateWrapper<User> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper
.set(User::getAge, 18)
.set(User::getEmail, "user@atguigu.com")
.like(User::getName, "a")
.and(i -> i.lt(User::getAge, 24).or().isNull(User::getEmail)); //lambda
表达式内的逻辑优先运算
User user = new User();
int result = userMapper.update(user, updateWrapper);
System.out.println("受影响的行数:" + result);
}
五、插件
1. 分页插件
- a >添加配置类
在Springboot配置类中放置对应bean组件
config包下MybatisPlusConfig
@Configuration
@MapperScan("com.zju.mybatisplus.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
- b >测试
mysql中分页:limit index,pageSize index=(当前页-1)*pageSize
@Test
public void testPage(){
//传入当前页和每页记录数
Page<User> page = new Page<>(2,3);
userMapper.selectPage(page,null);
//所有分页信息保存在page对象中
System.out.println(page);
//总记录:page.getRecords();
//当前页:page.getCurrent();
//每页显示的条数:page.getSize();
//总记录数:page.getTotal();
//总页数:page.getPages();
//是否有上一页:page.hasPrevious();
//是否有下一页:page.hasNext()
}
2. 自定义分页
根据年龄查询用户列表,分页显示
- a >UserMapper中定义接口方法
Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);
- b >UserMapper.xml中编写SQL
<sql id="BaseColumns">id,user_name,age,email</sql>
<!--Page<User> selectPageVo(@Param("page") Page<User> page,@Param("age") Integer age);-->
<select id="selectPageVo" resultType="User">
select <include refid="BaseColumns"></include> from t_user where age > #{age}
</select>
- c >测试
@Test
public void testSelectPageVo(){
//设置分页参数
Page<User> page = new Page<>(1, 5);
userMapper.selectPageVo(page, 20);
//获取分页数据
List<User> list = page.getRecords();
list.forEach(System.out::println);
}
3. 乐观锁
-
悲观锁:一个用户在操作数据过程中,另一个用户始终处于阻塞状态,等待其操作完成后才能操作。
-
乐观锁:用户更新数据时,同时会对版本号进行更新。后续操作数据时需要先匹配版本号。
实现流程:
a >修改实体类:加入@version
@TableName("t_product")
@Data
public class Product {
private Long id;
private String name;
private Integer price;
@Version
private Integer version;
}
b >添加乐观锁插件配置:
@Configuration
@MapperScan("com.zju.mybatisplus.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//添加分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
//添加乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
六、通用枚举
表中的某些字段是固定的,例如性别,可以用MP的通用枚举来实现
a >数据库中添加字段sex
b >创建通用枚举类型
@Getter
public enum SexEnum {
MALE(1,"男"),
FEMALE(2,"女");
@EnumValue
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}
c >配置扫描通用枚举
@EnumValue将注解标识的属性值存储到数据库中
mybatis-plus:
configuration:
# 配置MyBatis日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
global-config:
db-config:
# 配置mp主键策略
id-type: auto
type-aliases-package: com.zju.mybatisplus.pojo
# 配置扫描通用枚举
type-enums-package: com.zju.mybatisplus.enums
d >测试
@Test
public void testSexEnum(){
//数据库中存入性别字段的值是2
User user = new User(null,"wzz",24,"wzz@163.com",SexEnum.FEMALE,null);
userMapper.insert(user);
}
七、代码生成器
1. 引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
2. 快速生成
public class FastAutoGeneratorTest {
public static void main(String[] args) {
FastAutoGenerator.create("jdbc:mysql://localhost:3306/mybatis_plus?
serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false", "root", "123456")
.globalConfig(builder -> {
builder.author("godfu") // 设置作者
//.enableSwagger() // 开启 swagger 模式
.fileOverride() // 覆盖已生成文件
.outputDir("D://mybatis_plus"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.zju") // 设置父包名
.moduleName("mybatisplus") // 设置父包模块名
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, "D://mybatis_plus"));
// 设置mapperXml生成路径
})
.strategyConfig(builder -> {
builder.addInclude("t_user") // 设置需要生成的表名
.addTablePrefix("t_", "c_"); // 设置过滤表前缀
})
.templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
.execute();
}
}
八、多数据源
使用于多种场景:纯粹多库、读写分离、 一主多从、 混合模式等
场景说明:mybatis_plus数据库中有表t_user;mybatis_plus1数据库中有表product
a> 引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.5.0</version>
</dependency>
b> 配置多数据源
spring:
# 配置数据源信息
datasource:
dynamic:
# 设置默认的数据源或者数据源组,默认值即为master
primary: master
# 严格匹配数据源,默认false.true未匹配到指定数据源时抛异常,false使用默认数据源
strict: false
datasource:
master:
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
slave_1:
url: jdbc:mysql://localhost:3306/mybatis_plus_1?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
c> 指定操作的数据源
@DS可以注解在方法上或类上,同时存在就近原则方法上优先于类上注解
@DS("master") //指定所操作的数据源
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
@DS("slave_1")
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
}
九、MyBatisX
1. 快速代码生成
-
1. 配置好pom.xml和application.yml
-
2. 左边栏连接Database
- 3. 配置选项
配置生成项目路径、包名、项目结构
配置service,mapper接口和映射文件
自动生成mapper, pojo, service, serviceImpl, xml文件
2. 快速生成CRUD
在UserMapper中方法名需要见名识意(insert,delete,update,select)(Andxxx,,Byxxx),再ALT+enter补全方法中sql
public interface UserMapper extends BaseMapper<User> {
int insertSelective(User user);
int deleteByIdAndUserName(@Param("id") Long id, @Param("userName") String userName);
int updateAgeAndSexById(@Param("age") Integer age, @Param("sex") Integer sex, @Param("id") Long id);
List<User> selectAgeAndSexByAgeBetween(@Param("beginAge") Integer beginAge, @Param("endAge") Integer endAge);
List<User> selectAllByIdOrderByAgeDesc(@Param("id") Long id);
}