一、Springboot快速集成MybatisPlus
MybatisPlus官网
准备工作
step1:添加依赖
<!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>
step2:yml配置
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai username: root password: 123456 #控制台打印sql mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
step3:springboot启动类上添加自动扫描包
@MapperScan("xyz.changlu.mapper")
应用
Dao扩展配置类:可以直接直接调用方法查询数据库
//可以直接应用基本的CRUD public interface UserMapper extends BaseMapper<User> { }
service层扩展配置类:
其中QueryWrapper可以来配置一些条件筛选
//①继承IService,包含一些service封装好的方法 public interface UserService extends IService<User> { } @Service //①继承extends ServiceImpl<UserMapper, User>,封装好了IService中的一些接口 //②实现UserService public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { @Resource private UserMapper userMapper; @Override public List<User> getUserByName(String name) { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.select("id","name","age").like("name",name); //执行查询 List<User> users = userMapper.selectList(wrapper); return users; } }
二、分页
MybatisPlus官方文档(分页)
编写配置类:
/** * @author Administrator * @date 2021/07/26 16:36 **/ @Configuration @Component public class MybatisPlusConfig { // 最新版 @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } }
编写测试类:这里使用controller
@RestController @RequestMapping("/api/v1/test/my") public class UserController { @Autowired private UserMapper userMapper; @GetMapping("list") public ResultBody test(){ //设置Page实例 Page<User> page = new Page<>(2, 3); //调用Mapper分页查询 Page<User> userPage = userMapper.selectPage(page, null); userPage.getRecords().forEach(System.out::println);//getRecords()拿到分页查询的List集合 return ResultBody.success(userPage.getRecords()); } }