分页
1.引入pom
普通mvc项目引入
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
springboot引入
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
2.配置拦截器插件
在MyBatis的xml中配置拦截器插件
<plugins>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!--reasonable:分页合理化参数,默认值为false,直接根据参数进行查询。
当该参数设置为 true 时,pageNum<=0 时会查询第一页, pageNum>pages(超过总数时),会查询最后一页。-->
<!--<property name="reasonable" value="true"/>-->
</plugin>
</plugins>
3.使用
DbStudents 实体类
import lombok.Data;
@Data
public class DbStudents {
private Integer num;
private String name;
private Integer age;
private String birthday;
private String sex;
private String address;
private String major;
DbStudentsMapper 接口
package com.top.mapper;
import com.top.bean.DbStudents;
import java.util.List;
import org.springframework.stereotype.Repository;
@Repository
public interface DbStudentsMapper {
/**
* 多条件分页查询
* @param dbStudents
* @return
*/
List<DbStudents> showAllInfo(DbStudents dbStudents);
}
DbStudentsMapper.xml
注意:sql 中就不要写 limit 了,pageHelp 会自己处理,sql 就按正常查询写法就好
<!--多条件分页查询用户-->
<select id="showAllInfo" resultType="com.top.bean.DbStudents">
SELECT
<include refid="Base_Column_List"/>
FROM
db_students
<where>
<if test="num != null">
num = #{num,jdbcType=INTEGER},
</if>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null">
age = #{age,jdbcType=INTEGER},
</if>
<if test="birthday != null">
birthday = #{birthday,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="address != null">
address = #{address,jdbcType=VARCHAR},
</if>
<if test="major != null">
major = #{major,jdbcType=VARCHAR},
</if>
</where>
</select>
DbStudentsService 业务层接口
public interface DbStudentsService {
List<DbStudents> showAllInfo(DbStudents dbStudents);
}
DbStudentsServiceImpl 业务实现层
@Service
public class DbStudentsServiceImpl implements DbStudentsService {
@Autowired
private DbStudentsMapper dbStudentsMapper;
@Override
public List<DbStudents> showAllInfo(DbStudents dbStudents) {
return dbStudentsMapper.showAllInfo(dbStudents);
}
}
最后 DbStudentsController 控制层直接调用
/**
* 分页查询所有信息
*/
@RequestMapping("showAllInfo")
@ResponseBody
public PageInfo<DbStudents> showAllInfo(@RequestParam(value = "currentPage", required = false, defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", required = false, defaultValue = "3") Integer pageSize,
DbStudents dbStudents) {
// 使用mybatis的分页插件完成我们的分页查询
PageHelper.startPage(pageNum, pageSize);
List<DbStudents> employeeList = dbStudentsService.showAllInfo(dbStudents);
PageInfo<DbStudents> pageInfo = new PageInfo(employeeList);
return pageInfo;
}