依赖:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connectorjava</artifactId>
</dependency>
<!--mybatis plus和springboot整合-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-bootstarter</artifactId>
<version>3.4.1</version>
</dependency>
配置:
server.port=8884
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mysql?useUnicode=truecharacterEncoding=utf-8&useSSL=false
spring.datasource.username =admin
spring.datasource.password =123456
启动类配置扫描路径:@MapperScan("com.miao.test.mapper")
PO实体类添加: @TableName("student")
mapper :
public interface StudentMapper extends BaseMapper<StudentDO> {
}
QueryWrapper 查询包装类,可以封装多数查询条件
如: List<StudentDO> list =studentMapper .selectList(newQueryWrapper<StudentDO>());
多案例API查询
selectById
selectBatchIds
selectOne
selectCount
selectList
Mybatis plus 常⽤注解
@TableName ⽤于定义表名
@TableId ⽤于定义表的主键
属性: value ⽤于定义主键字段名
type ⽤于定义主键类型
IdType.AUTO 主键⾃增,系统分配,不需要⼿动输⼊
IdType.NONE 未设置主键
IdType.INPUT 需要⾃⼰输⼊ 主键值
IdType.ASSIGN_ID 系统分配 ID,⽤于数值型数据(Long,对应 mysql 中 BIGINT 类型)
IdType.ASSIGN_UUID 系统分配 UUID,⽤于字符串型数据(String,对应 mysql 中 varchar(32) 类型)
@TableField ⽤于定义表的⾮主键字段
属性:value ⽤于定义⾮主键字段名,⽤于别名匹配,假如java对象属性和数据库属性不⼀样
exist ⽤于指明是否为数据表的字段, true 表示是,false 为不是,假如某个java属性在数据库没对应的字段则要标记为false
fill ⽤于指定字段填充策略(FieldFill,⽤的不多)
字段填充策略:⼀般⽤于填充 创建时间、修改时间等字段
FieldFill.DEFAULT 默认不填充
FieldFill.INSERT 插⼊时填充
FieldFill.UPDATE 更新时填充
FieldFill.INSERT_UPDATE 插⼊、更新时填充。
删除操作
int rows = studentMapper .deleteById(4);
int rows = studentMapper .deleteByMap(Map);
更新操作
studentMapper .update(StudentDO,newQueryWrapper<StudentDO>().eq("id","2"));
UpdateWrapper updateWrapper = newUpdateWrapper();
updateWrapper.set("img","uuuu");
updateWrapper.eq("id",1);
studentMapper .update(null,updateWrapper);
QueryWrapper模糊查询
eq 等于
ne 不等于
gt ⼤于
ge ⼤于等于
lt ⼩于
le ⼩于等于
or 拼接or
between 两个值中间
notBetween 不在两个值中间
like 模糊匹配
notLike 不像
likeLeft 左匹配
likeRight 右边匹配
isNull 字段为空
in in查询
groupBy 分组
orderByAsc 升序
orderByDesc 降序
having having查询
如:
List<StudentDO> list = studentMapper.selectList(new QueryWrapper<StudentDO>().eq("id", "11").or().ne("age", 13));
分页插件配置类
@Configuration public class MybatisPlusPageConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
分页使用:
QueryWrapper<StudentDO> wrapper = newQueryWrapper<>();
wrapper.eq("age",4);
//第1⻚,每⻚10条
Page<StudentDO> page = new Page<>(1, 10);
IPage<StudentDO> iPage=studentMapper.selectPage(page, wrapper);