怎么在SpringBoot中集成Mybatis-plus
- 引入依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.2</version>
</dependency>
- 书写配置
//application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: Atguigu.123
url: jdbc:mysql://192.168.10.101:3306/hello_mp?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2b8
mybatis-plus内的注解
-
@TableName
:表名注解,用于标识实体类所对应的表value
:用于声明表名
-
@TableId
:主键注解,用于标识主键字段value
:用于声明主键的字段名type
:用于声明主键的生成策略,常用的策略有AUTO
、ASSIGN_UUID
、INPUT
等等
-
@TableField
:普通字段注解,用于标识属性所对应的表字段value
:用于声明普通字段的字段名
通用Mapper
- 查
//wrapper:查询构造器 IPage分页
selectList(Wrapper)
selectList(IPage,Wrapper)
//用id查数据,去TableName下匹配TableId对应的信息
selectById(id)
- 插
insert(BeanObject)
//批量插入 传入ID列表
saveBath(List)
//根据TableId进行匹配,存在ID则实现更新操作,没有ID实现增加操作
saveorupdate(BeanObject)
- 更
//通过传递Bean对象的ID进行修改操作
updateById(BeanObeject)
Wrapper条件构造器
QueryWrapper使用
//QueryWrapper 和 UpdateWrapper
//QueryWrapper只能用于查询、删除语句,UpdateWrapper还可用于set,更新语句
//查询name=tom的所有用户 .eq(column,value)
.list(new QueryWrapper<User>().eq("name","tom"))
//.eq(condition,column,value) : condition为true使用后面条件,反之不使用
.list(new QueryWrapper<User>().eq(true,"name","tom"))
//查询邮箱域名为 baomidou.com的所有用户 .like(colum,value)
.list(new QueryWrapper<User>().like("email",concat(email)))
// .ge(column,value) : 大于等于
// .le(colum,value) :小于等于
// .gt() : 大于
// .lt() : 小于
// .or() : 表名两个条件是或者的意思
new QueryWrapper<Object>().gt(colunm,value).or().lt(column,value)
new QueryWrapper<>().likeleft("email","").and(new Cu)
//排序 .orderBy()
//.orderByAsc()
//.orderByDesc()
UpdateWrapper使用:多用于更新操作
@AutoWierd
private ServiceImpl si;
UpdateWrapper<Bean> uw = new UpdateWrapper<>();
/*
uw.eq();
uw.like();
uw.lt();
uw.gt();
uw.ge();
uw.le();
uw.and();
uw.or();
*/
//new UpdateWrapper().set() 设置修改的字段与其对应的修改值
.set(column,value)
分页查询 : 把limit进行封装
- 引入分页配置
@Configuration
public class MPConfiguration {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
- 如何使用?
- BaseMapper接口和ServiceImpl实现类提供了进行分页的方法
//BaseMapper
// 传入IPage和条件构造器,返回IPage类型数据
IPage<T> selectPage(IPage<T> page,Wrapper<T> wrapper);
//ServiceImpl
IPage<T> Page(IPage<T> page);
IPage<T> Page(IPage<T> page,Wrapper<T> wrapper);
- 分页对象 IPage; 其实现类为Page
| 属性名 | 类型 | 默认值 | 描述 |
| records | List | emptyList | 查询数据列表 |
| total | Long | 0 | 查询列表总记录数 |
| size | Long | 10 | 每页显示条数,默认10
|
| current | Long | 1 | 当前页 |
星星:
- 添加SQl语句日志
mybatis-plus:
configuration:
log-impl:
- 修改Mapper.xml文件的映射地址
mybatis-plus:
mapper-location: classpath*:/mapper/**/*.xml