mybatis

springboot怎么整合mybatisplus分页

小亿
107
2024-08-11 12:54:38
栏目: 编程语言

Spring Boot整合MyBatis-Plus实现分页功能的步骤如下:

  1. 首先,在pom.xml文件中添加MyBatis-Plus和MyBatis-Plus的分页插件的依赖:
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus-version}</version>
</dependency>
  1. 在application.properties文件中配置MyBatis-Plus的配置信息:
#MyBatis-Plus配置
mybatis-plus.mapper-locations=classpath*:/mapper/**/*.xml
mybatis-plus.type-aliases-package=com.example.domain
  1. 创建一个Mapper接口,使用MyBatis-Plus提供的BaseMapper接口,并在接口中定义分页查询方法:
public interface UserMapper extends BaseMapper<User> {
    IPage<User> selectUserPage(Page<User> page, @Param("name") String name);
}
  1. 在对应的Mapper.xml文件中编写分页查询的SQL语句:
<select id="selectUserPage" resultType="com.example.domain.User">
    SELECT *
    FROM user
    WHERE name = #{name}
</select>
  1. 在Service层中调用Mapper接口中定义的分页查询方法:
@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    public IPage<User> getUserPage(Page<User> page, String name) {
        return userMapper.selectUserPage(page, name);
    }
}
  1. 在Controller层中调用Service层中定义的方法,获取分页数据:
@RestController
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/users")
    public IPage<User> getUsers(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam String name) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return userService.getUserPage(page, name);
    }
}

通过以上步骤,就可以在Spring Boot项目中实现MyBatis-Plus的分页功能。

0
看了该问题的人还看了