MybatisPlus的使用
引入坐标依赖
<!-- mybatis-plus 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!-- mysql驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
配置文件
server:
port: 8082
servlet:
context-path: /mp
# 数据源配置
spring:
datasource:
username: mysql
password: mysql
url: jdbc:mysql://localhost:3306/ssm?allowPublicKeyRetrieval=true&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
# MybatisPlus
mybatis-plus:
global-config:
db-config:
column-underline: true # 驼峰形式
logic-delete-field: isDeleted # 全局逻辑删除的实体字段名
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
db-type: mysql
id-type: assign_id # id策略
table-prefix: t_ # 配置表的默认前缀
mapper-locations: classpath*:/mapper/**Mapper.xml # mapper 文件位置
type-aliases-package: xxx.xxx.entity # 实体类别名
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志:打印sql 语句
创建Mapper接口,需要继承BaseMapper< entity >
@Mapper
public interface XxxMapper excents BaseMapper<Xxx>{}
注意:
(1)、因为 mybatis 规定:mapper.xml 文件的名字要和接口名字一样,所以很多人习惯将 Dao 接口命名为
xxxMapper
。(2)、BaseMapper 是 MybatisPlus 内置的接口,它包含基本的 CRUD 方法。
启动类添加 @MapperScan 注解
@SpringBootApplication
@MapperScan("xx.xx.mapper")
publuc class Application{}
新增数据 insert
userMapper.insert(user);
编辑数据 updateById
int rows = userMapper.updateById(user);
删除数据 deleteById
userMapper.deleteById("1");
根据 map 条件删除信息 deleteByMap
Map<String, Object> param = new HashMap<>();
param.put("age", 18);
int rows = userMapper.deleteByMap(param);
根据 id 集合批量删除 deleteBatchIds
List<Integer> ids = Stream.of(110, 112, 113, 115).collect(Collectors.toList());
int rows = userMapper.deleteBatchIds(ids);
根据 id 查询 selectById
User user = userMapper.selectById(1);
根据 map 条件查询 selectByMap
Map<String, Object> param = new HashMap<>();
param.put("age", 18);
List<User> userList = userMapper.selectByMap(param);
根据 id 集合批量查询 selectBatchIds
List<Integer> ids = Stream.of(110, 112, 113, 115).collect(Collectors.toList());
List<User> userList = userMapper.selectBatchIds(ids);
继承 MybatisPlus 的BaseMapper,就能完成基本的增删改查操作
**构造器 QueryWrapper
**
MybatisPlus 提供了**「查询构造器」和「更新构造器」**用来生成带有 where 条件的 sql 语句。
常用查询条件:
等于:eq
-> equals
// 查询名字为张三的用户
List<User> userList = userMapper.selectList(new QueryWrapper<>().eq("name","张三"));
不等于:ne
-> not equals
// 查询名字不是张三的用户
List<User> userList = userMapper.selectList(new QueryWrapper<>().ne("name","张三"));
模糊查询:like
List<User> userList = userMapper.selectList(new QueryWrapper<>().like("name","张"));
降序:orderByDesc
// 查询姓名不等于张三的,并按照age倒序排序
List<User> userList = userMapper.selectList(new QueryWrapper<>().ne("name","张三").orderByDesc("age"));
升序:orderByAsc
// 查询姓名不等于张三的,并按照age升序排序
List<User> userList = userMapper.selectList(new QueryWrapper<>().ne("name","张三").orderByAsc("age"));
其他常用的条件可以去官网查看相关文档:https://baomidou.com/pages/10c804/#in
**更新条件的构造器 UpdateWrapper
**
UpdateWrapper
的 where
条件和 QueryWrapper
的一样,只不过需要 set
值。
UpdateWrapper<User> userWrapper = new UpdateWrapper<>();
userWrapper.set("name","王小波").set("age",22).eq("name","张三");
通用 Service
创建Service接口,需要继承Iservice < entity >
public interface XxxService extends IService<Xxx> {}
创建IService接口实现类UserServiceImpl,实现IService方法
@Service
public class XxxServiceImpl extends ServiceImpl<XxxMapper, Xxx> implements XxxService {}
常用注解:
@TableName
:如果实体类和数据库的表名不一致,可以使用这个注解做映射
@TableField
:当表属性和实体类中属性名不一致时,可以使用这个注解做映射
@TableId
:表示 id 的生成策略:雪花算法策略随机生成和自增(IdType.ASSIGN_ID、IdType.AUTO)
@TableName("tb_user")
public class User{
@TableId(value="id",type=IdType.AUTO)
private Long id;
@TableField("username")
private String name;
}
分页:
MybatisPlus 内部封装了分页插件,只用简单配置一下就能实现分页功能。
配置类
@Configuration
@MapperScan("xxx.xxx.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new
PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
测试分页
@Test
void testMybatisPlus() {
int current = 1;
int size = 10;
Page<User> userPage = new Page<>(current, size);
//获取分页数据
List<User> list = userPage.getRecords();
list.forEach(user->{
System.out.println(user);
});
Page<User> page = userMapper.selectPage(userPage, null);
System.out.println("当前页:" + page.getCurrent());
System.out.println("每页条数:" + page.getSize());
System.out.println("总记录数:" + page.getTotal());
System.out.println("总页数:" + page.getPages());
}
遇到的坑:
1、传参为 0 时,查询语句失效。例如传递的 age 为 0,查询就会失效
原因:判断 int 是否为空只要 !=null 就行了,如果加上 age != ‘’,
0 会被转为 null
。
2、MybatisPlus 更新字段为 null 失败.
解决办法:updateStrategy = FieldStrategy.IGNORED
该注解会忽略为空的判断
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String name;