使用MyBatis的分页功能

(1)pom依赖(maven添加依赖):

<dependency>
<groupId>com.github.miemiedev</groupId>
<artifactId>mybatis-paginator</artifactId>
</dependency>

(2)applicationContext-dao.xml中(spring加载配置信息):

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />

</bean>

(3)SqlMapConfig.xml中(配置信息放在xml中):

<configuration>
<plugins>
<!-- com.github.pagehelper 为 PageHelper 类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL 六种数据库-->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>

</configuration>

(4)定义实体类 PageResult:

package entity;
import java.io.Serializable;
import java.util.List;
public class PageResult implements Serializable{
private long total;
private List rows;
public PageResult(long total, List rows) {
super();
this.total = total;
this.rows = rows;
}
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
}

(5)interface中:

public PageResult findPage(int pageNum, int pageSize);

service中重写interface中的方法:

@Override
public PageResult findPage(int pageNum, int pageSize) {
//这行代码相当于是做了初始配置,后面的代码不受其影响
PageHelper.startPage(pageNum, pageSize);

Page<TbBrand> page = (Page<TbBrand>) brandMapper.selectByExample(null);

return new PageResult(page.getTotal(), page.getResult());
}

(6)在controller中进行调用:

@RequestMapping("/findPage")
public PageResult findPage(int page, int size){
return brandService.findPage(page, size);
}

猜你喜欢

转载自blog.csdn.net/jiuweideqixu/article/details/80648741