分页查询在实际开发中是必不可少的一项功能,本文在SpringBoot2.x搭建SSM项目上继续整合PageHelper实现分页
https://github.com/pagehelper/Mybatis-PageHelper
https://github.com/qidasheng2012/springboot2.x_ssm/tree/branch-page
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelper-spring-boot-starterartifactId>
<version>1.2.12version>
dependency>
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countsql
package com.springboot.ssm.controller;
import com.github.pagehelper.PageInfo;
import com.springboot.ssm.domain.User;
import com.springboot.ssm.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/toUserListPage")
public String toUserListPage() {
return "user/userList";
}
@GetMapping("/getAll")
@ResponseBody
public List<User> getAll() {
return userService.getAll();
}
@GetMapping("/page")
@ResponseBody
public PageInfo<User> page(User user, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
return userService.page(user, pageNum, pageSize);
}
}
package com.springboot.ssm.service;
import com.github.pagehelper.PageInfo;
import com.springboot.ssm.domain.User;
import java.util.List;
public interface UserService {
// 查询所有用户信息
List<User> getAll();
// 分页查询用户信息
PageInfo<User> page(User user, Integer pageNum, Integer pageSize);
}
package com.springboot.ssm.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.ssm.domain.User;
import com.springboot.ssm.mapper.UserMapper;
import com.springboot.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> getAll() {
return userMapper.getAll();
}
@Override
public PageInfo<User> page(User user, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> list = userMapper.getUsers(user);
return PageInfo.of(list);
}
}
package com.springboot.ssm.mapper;
import com.springboot.ssm.domain.User;
import java.util.List;
public interface UserMapper {
// 查询所有用户信息
List<User> getAll();
// 根据条件查询用户信息
List<User> getUsers(User user);
}
<mapper namespace="com.springboot.ssm.mapper.UserMapper">
<select id="getAll" resultType="User">
SELECT
id,
name,
age
FROM user
select>
<select id="getUsers" resultType="User" parameterType="User">
SELECT
id,
name,
age
FROM user
<where>
<if test="name != null and name != ''">
and name = #{name}
if>
<if test="age != null">
and age = #{age}
if>
where>
select>
mapper>