分为三步:
一:在pom.xml中添加依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
二:在config层中添加MybatisPlusConfig.xml文件
package com.wu.springboot.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.wu.springboot.mapper")
public class MybatisPlusConfig {
//最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
三:在具体的使用
1.如果实体类的名字和数据库的表格名字一致可以不用管这步骤,否则在实体类User,需要加注解@@TableName(value = “sys_user”) sys_user是数据库的名字,在实体属性名主键前+@TableId (type = IdType.AUTO)//指定主键类型
2.在service层直接使用方法 例如:saveOrUpdate(user); save(user)
3.在controller层直接用userService.方法
userService.saveUser(user);
@GetMapping("/page")
public IPage<User> findPage(@RequestParam Integer pageNum,
@RequestParam Integer pageSize,
@RequestParam(defaultValue = "") String username,//传默认值为空,否则三选一传参数的时候会报错
@RequestParam(defaultValue = "") String email,
@RequestParam(defaultValue = "") String address
) {
IPage<User> page = new Page<User>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
if(!"".equals(username)){
queryWrapper.like("username", username);
}
if (!"".equals(email)){
queryWrapper.like("email",email);
}
if (!"".equals(address)){
queryWrapper.like("address",address);
}
return userService.page(page,queryWrapper);