Mybatis-Plus入门
1、 什么是mybatisplus
是基于mybatis框架基础上开发的增强型工具,简化开发,提高效率。
2、引入mybatisplus
在springboot项目中,引入mybatisplus。
① 导入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
②编写yml文件
配置数据库信息
spring: #数据库信息
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
username: root
password: root
# 开启mp的日志(输出到控制台)
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
③编写实体类
④Dao层开发需要继承BaseMapper<实体类>
@Mapper
public interface BookDao extends BaseMapper<Book> {
}
3、关于mybatisplus的CRUD(增删改查)
新增
@Test
public void save(){
User user = new User();
user.setUsername("name");
user.setPassword("123");
userDao.insert(user);
}
注:新增时,可能会出现id生成策略,在mybatisplus中,自动封装了id生成策略。
自动输入id:type = IdType.INPUT
uuid:type = IdType.ASSIGN_UUID
自增:type = IdType.AUTO
雪花算法:type = IdType.ASSIGN_ID
@TableId(type = IdType.ASSIGN_ID)//雪花算法:64位
private int id;
或者在yml文件中配置全局变量
global-config:
db-config:
id-type: assign_uuid
#sql表名与实体类匹配:前缀
table-prefix: tbl_
删除
①根据id进行删除
//删除id
@Test
public void delete(){
int i = userDao.deleteById(4);
System.out.println(i);
}
②多个删除
userDao.deleteBatchIds(list);
修改
//修改
@Test
public void update(){
User user = new User();
user.setId(24);
user.setUsername("修改name");
int i = userDao.updateById(user);
System.out.println(i);
}
查询
①简单查询:根据id查询、查询所有
//查询所有
@Test
public void selectAll(){
List<User> users = userDao.selectList(null);
System.out.println(users);
}
//根据id进行查询
@Test
public void selectById(){
User user = userDao.selectById(24);
System.out.println(user);
}
②条件查询
a)
lt:小于 、gt:大于、le:小于等于、ge:大于等于。
or:.or()或者 and:直接链式编程
b)
当查询条件有null时
有上下限的属性(年龄、价格…),需要再创建一个实体类继承原来的实体类
c)查询投影
查询出现显示的列
分页查询
①需要配置分页拦截器,才可实现分页查询
在config中配置分页拦截器
@Configuration
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor(){
//定义mp拦截器
MybatisPlusInterceptor mp = new MybatisPlusInterceptor();
//添加具体拦截器
mp.addInnerInterceptor(new PaginationInnerInterceptor());
return mp;
}
②进行分页查询
//分页查询
@Test
public void Page(){
IPage page = new Page(1,2); //参数一:第几页 参数二:显示条数
userDao.selectPage(page,null);
List records = page.getRecords();
System.out.println(records);
}
4、字段映射
在实体类中
a、实体类与数据库表进行对应:
@TableName("user")//对应数据库的表名称
b、数据库字段与实体类字段不一致时:
// @TableField(value = "userName")
private String username;
c、不显示某一个实体类字段时:
@TableField(select = false)
private String password;
d、当字段在数据库中不存在时:
@TableField(exist = false)
private Integer online;
e、逻辑删除时:
@TableLogic(value = "0",delval = "1")
private Integer deleted;
5、乐观锁
出现并发问题的时候,我们可以使用乐观锁
①在数据库中添加字段version
②在实体类中添加version字段,并在字段上加注解@version
③添加乐观锁的拦截器
//乐观锁拦截器
mp.addInnerInterceptor(new OptimisticLockerInnerInterceptor());