1.导入jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</exclusion>
<exclusion>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</exclusion>
</exclusions>
</dependency>
2.mybatis-config.xml文件中配置拦截器interceptor
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!--设置数据库类型-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
3.测试类中调用startPage()方法
@Test
public void pageSelect(){
Page<User> startPage = PageHelper.startPage(3,3);
Page<User> users = userMapper.selectByPage();
System.out.println(users);
}
4.分析
-
PageHelper继承PageMethod类
public class PageHelper extends PageMethod
-
PageMethod类中有Page类型的静态方法,子类可以继承startPage
public static <E> Page<E> startPage(int pageNum, int pageSize) {
return startPage(pageNum, pageSize, DEFAULT_COUNT);
}
- 调用
Page<E> pageStart = PageHelper.startPage(int pageNum, int pageSize)
可以实现分页查询 - Page类的源码属性如下:
public class Page<E> extends ArrayList<E> implements Closeable {
private static final long serialVersionUID = 1L;
//当前页码
private int pageNum;
//当前页对应的信息条数
private int pageSize;
//起始页码
private int startRow;
//终止页码
private int endRow;
//查询信息的总条数
private long total;
//分页的总页数
private int pages;
private boolean count;
private Boolean reasonable;
private Boolean pageSizeZero;
private String countColumn;
private String orderBy;
private boolean orderByOnly;
................
}
动态查询
查询集合
例:select * from user where id in{1,2,3,4,6,10};
<select id="findByForeachTable" resultType="com.pojo.User" parameterType="user">
select * from user
<where>
<if test="list != null">
<foreach collection="list" open=" and id in (" close=")" separator=",">
#{id}
</foreach>
</if>
</where>
</select>
根据名称和性别查询
<select id="findByCondition" parameterType="com.pojo.User" resultType="user">
select * from user
<where>
<if test="user_name !=null">
and user_name = #(userName)
</if>
<if test="user_sex != null">
and user_sex = #{userSex}
</if>
</where>
</select>