Spring Boot+SSM+MyBatis-Plus 实现分页查询
在Spring Boot项目中使用SSM(Spring + Spring MVC + MyBatis)和MyBatis-Plus实现分页查询,你需要做以下几步:
- 添加依赖:确保
pom.xml
中包含MyBatis-Plus的分页插件依赖。
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>你的版本号</version>
</dependency>
- 配置分页插件:在MyBatis-Plus的配置类中添加分页插件。
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
- 使用分页:在Mapper接口中定义分页查询方法,并在Service中调用。
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Select;
public interface UserMapper extends BaseMapper<User> {
@Select("SELECT * FROM user")
IPage<User> selectPageVo(Page<?> page);
}
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public IPage<User> selectUserPage(int current, int size) {
Page<User> page = new Page<>(current, size);
return userMapper.selectPageVo(page);
}
}
- 控制器中使用Service进行分页查询。
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public IPage<User> getUsers(@RequestParam int current, @RequestParam int size) {
return userService.selectUserPage(current, size);
}
}
以上代码实现了在Spring Boot项目中使用MyBatis-Plus进行分页查询的基本流程。你需要根据自己的实际情况调整Mapper接口中的SQL语句和Service中的方法。
评论已关闭