MyBatisPlus分页插件
1.MyBatis插件
在 MyBatis-Plus 中,你可以使用 XML 来配置分页查询,并在 Controller、Service 和 Mapper 中协同工作以实现分页功能。以下是如何在这三个层级中结合使用 MyBatis-Plus 的 XML 配置来实现分页查询:
1.1 SpringBoot
@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
// 旧版
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
在 Mapper 中配置分页查询方法
1.2 XML Mapper 文件中的配置
<!-- UserMapper.xml -->
<mapper namespace="com.example.demo.mapper.UserMapper">
<select id="selectUserPage" resultType="com.example.demo.User">
select * from user
<where>
<if test="name != null and name != ''">
and name like concat('%', #{name}, '%')
</if>
</where>
order by id
</select>
</mapper>
在 Service 中调用分页查询方法
1.3 Service 层中的调用
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public IPage<User> getUserList(String name, Integer currentPage, Integer pageSize) {
Page<User> page = new Page<>(currentPage, pageSize);
return userMapper.selectUserPage(page, name);
}
}
在 Controller 中调用 Service 层方法
1.4 Controller 中的调用
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public IPage<User> getUsers(@RequestParam String name, @RequestParam Integer currentPage, @RequestParam Integer pageSize) {
return userService.getUserList(name, currentPage, pageSize);
}
}
1.5 UserMapper 接口中添加方法以支持分页查询:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.User;
public interface UserMapper extends BaseMapper<User> {
IPage<User> selectUserPage(Page<User> page, @Param("name") String name);
}
在这个示例中,我们扩展了 MyBatis-Plus 的 BaseMapper 接口,并添加了一个名为 selectUserPage 的方法来实现分页查询。该方法接收一个 Page 对象用于分页信息,以及一个名为 name 的参数用于条件查询。
在这个示例中,Controller 负责接收请求并调用 Service 层的方法,而 Service 层则调用 Mapper 中定义的分页查询方法。通过这种方式,实现了分层架构下的分页查询功能,使代码更加清晰和易于维护。