目录
入门:
使用MybatisPlus的基本步骤:
1.引入MybatisPlus的起步依赖
MyBatisPlus官方提供了starter,其中集成了Mybatis和MybatisPlus的所有功能,并且实现了自动装配效果。
因此我们可以用MybatisPlus的starter代替Mybatis的starter:
<!--MybatisPlus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
2.定义Mapper
自定义的Mapper继承MybatisPlus提供的BaseMapper接口:
public interface UserMapper extends BaseMapper<User> {
}
常见注解
MyBatisPlus通过扫描实体类,并基于反射获取实体类信息作为数据库表信息。
MybatisPlus中比较常用的几个注解如下:
•
@TableName
:用来指定表名
@TableName("tb_user")
public class User {
}
•
@TableId
:用来指定表中的主键字段信息
@TableId(value = "id", type = IdType.AUTO)
private Long uid;
IdType枚举:
•AUTO:数据库自增长
•INPUT:通过set方法自行输入
•ASSIGN_ID:分配 ID,接口IdentifierGenerator的方法nextId来生成id,默认实现类为DefaultIdentifierGenerator雪花算法
•
@TableField
:用来指定表中的普通字段信息
@TableField("username")
private String name;
@TableField("is_married")
private Boolean isMarried;
@TableField("`order`")
private Integer order;
@TableField(exist = false)
private String address;
使用@TableField的常见场景:
•成员变量名与数据库字段名不一致
•成员变量名以is开头,且是布尔值
•成员变量名与数据库关键字冲突
•成员变量不是数据库字段
常见配置
MyBatisPlus的配置项继承了MyBatis原生配置和一些自己特有的配置。例如:
mybatis-plus:
type-aliases-package: com.itheima.mp.domain.po #别名扫描包
mapper-locations: classpath*:/mapper/**/*.xml #Mapper.xml文件地址,默认值
configuration:
map-underscore-to-camel-case: true #是否开启下划线和驼峰的映射
cache-enabled: false #是否开启二级缓存
global-config:
db-config:
id-type: auto #id为雪花算法生成
update-strategy: not_null #更新策略:只更新非空字段
总结
MyBatisPlus使用的基本流程是
①
引入起步依赖
②
自定义
Mapper
基础
BaseMapper
③
在实体类上添加注解声明 表信息
④
在
application.yml
中根据需要添加配置
核心功能
条件构造器
MyBatisPlus支持各种复杂的where条件,可以满足日常开发的所有需求。
条件构造器的用法:
•
QueryWrapper
和
LambdaQueryWrapper
通常用来构建
select
、
delete
、
update
的
where
条件部分
@Test
void testQueryWrapper(){
//1.构建条件查询
QueryWrapper<User> wrapper = new QueryWrapper<User>()
.select("id", "username", "info", "balance")
.like("username", "l")
.ge("balance", 100);
//2.查询
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
@Test
void testLambdaQueryWrapper(){
//1.构建条件查询
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<User>()
.select(User::getId, User::getUsername, User::getInfo, User::getBalance)
.like(User::getUsername, "l")
.ge(User::getBalance, 100);
//2.查询
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
•
UpdateWrapper
和
LambdaUpdateWrapper
通常只有在
set
语句比较特殊才使用
@Test
void testUpdateByQueryWrapper(){
//1.要更新的数据
User user = new User();
user.setBalance(2000);
//2.更新的条件
QueryWrapper<User> wrapper = new QueryWrapper<User>().eq("username", "jack");
//3.执行更新
userMapper.update(user, wrapper);
}
@Test
void testUpdateWrapper(){
List<Long> ids = List.of(1L,2L,4L);
UpdateWrapper<User> wrapper = new UpdateWrapper<User>()
.setSql("balance = balance - 100")
.in("id", ids);
userMapper.update(null, wrapper);
}
•
尽量使用
LambdaQueryWrapper
和
LambdaUpdateWrapper
,避免硬编码
自定义SQL
我们可以利用MyBatisPlus的Wrapper来构建复杂的Where条件,然后自己定义SQL语句中剩下的部分。
①
基于
Wrapper
构建
where
条件
@Test
void testCustomSqlUpdate(){
//1.更新数据条件
List<Long> ids = List.of(1L,2L,4L);
int amount = 200;
//2.定义条件
QueryWrapper<User> wrapper = new QueryWrapper<User>().in("id", ids);
userMapper.updateBalanceByIds(wrapper, amount);
}
②
在
mapper
方法参数中用
Param
注解声明
wrapper
变量名称,必须是
ew
void updateBalanceByIds(@Param("ew") QueryWrapper<User> wrapper, @Param("amount") int amount);
③
自定义
SQL
,并使用
Wrapper
条件
<update id="updateBalanceByIds">
update tb_user set balance = balance - #{amount} ${ew.customSqlSegment}
</update>
Service接口
IService接口基本用法
MP的Service接口使用流程:
自定义
Service
接口继承
IService
接口
public interface IUserService
extends IService<User> {}
自定义Service实现类,实现自定义接口并继承ServiceImpl
类
public class UserServiceImpl
extends ServiceImpl<UserMapper, User>
implements IUserService {...}
IService的Lambda查询
lambdaQuery()
.like(name != null,User::getUsername,name)
.eq(status != null,User::getStatus,status)
.ge(minBalance != null,User::getBalance,minBalance)
.le(maxBalance != null,User::getBalance,maxBalance)
.list();
IService的Lambda更新
lambdaUpdate()
.set(User::getBalance, remainBalance)
.set(remainBalance == 0,User::getStatus, 2)
.eq(User::getId, id)
.eq(User::getBalance , user.getBalance())
.update();
IService批量新增
•
普通
for
循环插入
普通for循环逐条插入速度极差,不推荐
•
IService
的批量插入
MP的批量新增,基于预编译的批处理,性能不错
配置jdbc参数,开rewriteBatchedStatements,性能最好