Mybatis分页插件PageHelper使用

1,配置PageHelper分页插件:

Config PageHelper

//在mybatis配置文件添加配置
1. Using in mybatis-config.xml

<!-- 
    In the configuration file, 
    plugins location must meet the requirements as the following order:
    properties?, settings?, 
    typeAliases?, typeHandlers?, 
    objectFactory?,objectWrapperFactory?, 
    plugins?, 
    environments?, databaseIdProvider?, mappers?
-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!-- config params as the following -->
        <property name="param1" value="value1"/>
    </plugin>
</plugins>

//在spring配置文件添加配置
2. Using in Spring application.xml

config org.mybatis.spring.SqlSessionFactoryBean as following:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <!-- other configuration -->
  <property name="plugins">
    <array>
      <bean class="com.github.pagehelper.PageInterceptor">
        <property name="properties">
          <!-- config params as the following -->
          <value>
            param1=value1
          </value>
        </property>
      </bean>
    </array>
  </property>
</bean>

这里选第一种方法,可直接复制文件 文件名:Mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<!-- 打印查询语句 -->
		<setting name="logImpl" value="STDOUT_LOGGING" />
	</settings>

	<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>

使用插件:

编写mapper.xml文件

<select id="selectByPageAndSelections" resultMap="BaseResultMap">
        SELECT *
        FROM doc
        ORDER BY doc_abstract
    </select>

然后在Mapper.java中编写对应的接口

public List<Doc> selectByPageAndSelections();

测试

@Service
public class DocServiceImpl implements IDocService {
    @Autowired
    private DocMapper docMapper;

    @Override
    public PageInfo<Doc> selectDocByPage1(int currentPage, int pageSize) {
        //先设置插件, currentPage为第几页, pageSize 每页大小
        PageHelper.startPage(currentPage, pageSize);
        List<Doc> docs = docMapper.selectByPageAndSelections();
        //组装PageInfo, 里面包含了很多数据,包括总页数一系列数据,可查看类获取
        PageInfo<Doc> pageInfo = new PageInfo<>(docs);
        return pageInfo;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值