SSM使用mybatis分页插件pagehepler实现分页示例

前几天在这里分享了手写 sql 分页查询实现分页,现在来看看使用 mybatis 分页插件 pagehepler 来实现分页

使用分页插件的原因,简化了sql代码的写法,实现较好的物理分页,比写一段完整的分页sql代码,也能减少了误差性。

Mybatis分页插件 demo 项目地址:free-Mybatis_PageHelper_jb51.rar

我这里使用 maven 工程实现:

1.首先导入分页插件的依赖:

<dependency>
  <groupId>com.github.pagehelper</groupId>
  <artifactId>pagehelper</artifactId>
  <version>5.0.0</version>
 </dependency>

2.配置分页拦截器插件

官方文档有两种配置分页拦截器插件

1. 在 MyBatis 配置 xml 中配置拦截器插件

<!-- 
 plugins在配置文件中的位置必须符合要求,否则会报错,顺序如下:
 properties?, settings?, 
 typeAliases?, typeHandlers?, 
 objectFactory?,objectWrapperFactory?, 
 plugins?, 
 environments?, databaseIdProvider?, mappers?
-->
<plugins>
 <!-- com.github.pagehelper为PageHelper类所在包名 -->
 <plugin interceptor="com.github.pagehelper.PageInterceptor">
  <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 -->
  <property name="param1" value="value1"/>
 </plugin>
</plugins>

2. 在 Spring 配置文件中配置拦截器插件

使用 spring 的属性配置方式,可以使用 plugins 属性像下面这样配置:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
 <!-- 注意其他配置 -->
 <property name="plugins">
 <array>
  <bean class="com.github.pagehelper.PageInterceptor">
  <property name="properties">
   <!--使用下面的方式配置参数,一行配置一个 -->
   <value>
   params=value1
   </value>
  </property>
  </bean>
 </array>
 </property>
</bean>

这里我项目中使用的是第二种,里面的参数根据实际情况配置,也可以不配置

3.调用方法

mapper 层 sql 语句按照一般查询写法,不用写分页:

<!-- 分页查询 -->
 <select id="finds" resultType="country">
  SELECT
   id,
   countryname,
   countrycode
  FROM
   country
 </select>

mapper 层接口:

/**
 * 查询
 * @param params
 * @return
*/
public List<Country> finds();

service 业务层接口:

 /**
 * 分页查询
 * @param params 分页参数 pageNo(页码),pageSize(每页查询数目)
 * @return
 */
 public PageInfo<Country> finds(Params params);

service 业务层实现类:PageHelper.startPage(1, 10);第一个参数表示第几页,第二个参数表示每页显示的记录数

执行完 PageHelper.startPage(1, 10);语句后,紧跟着的第一个select方法会被分页:List<Country> blogs = countryMapper.finds();

然后再用 PageInfo 对查询结果进行包装,PageInfo<Country> pageInfo = new PageInfo<Country>(blogs);

并将 pageInfo 返回到控制层

/**
  * 查询
  */
 public PageInfo<Country> finds(Params params)   
  //查询
  int pageNo = params.getPageNo();
  int pageSize = params.getPageSize();  
  PageHelper.startPage(pageNo, pageSize);
  List<Country> blogs = countryMapper.finds();
  //用PageInfo对结果进行包装
  PageInfo<Country> pageInfo = new PageInfo<Country>(blogs);
  return pageInfo;
  }

这里返回 pageInfo 后,在 controller 层传入 params 分页参数 和 解析 pageInfo:

List<Country> clist = pageInfo.getList(); 再将 clist 放进作用域,在前台页面利用<c:forEach></c:forEach>可循环获得分页数据
/**
  * 首页,并且分页查询
  * @return
  */
 @RequestMapping("/index")
 public ModelAndView index(Params params){  ModelAndView modelAndView = new ModelAndView();
  //一开始第一页,查询10条
  params.setPageNo(1);
  params.setPageSize(10);
  PageInfo<Country> pageInfo = countryService.finds(params);
  List<Country> clist = pageInfo.getList();
  //查询数量
  long couts = countryService.counts();
  modelAndView.addObject("clist", clist);
  modelAndView.addObject("couts", couts);
  modelAndView.setViewName("index");  
  return modelAndView;
 }

上面说的都是关键分页的实现代码,现在看看全部配置和实现的代码:

pom.xml

<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.krry</groupId>
 <artifactId>maven_pagehepler_ora</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>maven_pagehepler_ora</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <!-- MyBatis Generator -->
  <!-- Java接口和实体类 -->
  <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
  <targetMapperPackage>com.isea533.mybatis.mapper</targetMapperPackage>
  <targetModelPackage>com.isea533.mybatis.model</targetModelPackage>
  <!-- XML生成路径 -->
  <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
  <targetXMLPackage>mapper</targetXMLPackage>
  <!-- 编译jdk版本 -->
  <jdk.version>1.6</jdk.version>
  <!-- 依赖版本 -->
  <mybatis.version>3.3.1</mybatis.version>
  <mapper.version>3.3.6</mapper.version>
  <pagehelper.version>5.0.0</pagehelper.version>
  <mysql.version>5.1.29</mysql.version>
  <spring.version>4.1.2.RELEASE</spring.version>
  <mybatis.spring.version>1.2.4</mybatis.spring.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.11</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>log4j</groupId>
   <artifactId>log4j</artifactId>
   <version>1.2.17</version>
  </dependency>

  <!--web-->
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>servlet-api</artifactId>
   <version>2.5</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet.jsp</groupId>
   <artifactId>jsp-api</artifactId>
   <version>2.1</version>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
   <version>1.2</version>
  </dependency>
  <dependency>
   <groupId>javax.ws.rs</groupId>
   <artifactId>javax.ws.rs-api</artifactId>
   <version>2.0</version>
  </dependency>
  <dependency>
   <groupId>javax.websocket</groupId>
   <artifactId>javax.websocket-api</artifactId>
   <version>1.0</version>
  </dependency>
  <dependency>
   <groupId>javax.annotation</groupId>
   <artifactId>javax.annotation-api</artifactId>
   <version>1.2</version>
  </dependency>
  <dependency>
   <groupId>javax.transaction</groupId>
   <artifactId>javax.transaction-api</artifactId>
   <version>1.2</version>
  </dependency>

  <!--Spring-->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-orm</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-oxm</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jdbc</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-tx</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-aop</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-test</artifactId>
  </dependency>

  <!--spring-oxm依赖-->
  <dependency>
   <groupId>org.codehaus.castor</groupId>
   <artifactId>castor-xml</artifactId>
   <version>1.3.3</version>
  </dependency>
  <!--spring-json依赖-->
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.4.2</version>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.dataformat</groupId>
   <artifactId>jackson-dataformat-xml</artifactId>
   <version>2.4.2</version>
  </dependency>
  <!--spring-aop依赖-->
  <dependency>
   <groupId>org.aspectj</groupId>
   <artifactId>aspectjweaver</artifactId>
   <version>1.8.2</version>
  </dependency>

  <!--上传文件-->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>

  <!--mysql-->
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>${mysql.version}</version>
  </dependency>
  
  <!--druid-->
  <dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.11</version>
  </dependency>

  <!--Mybatis-->
  <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis</artifactId>
   <version>${mybatis.version}</version>
  </dependency>
  <dependency>
   <groupId>org.mybatis</groupId>
   <artifactId>mybatis-spring</artifactId>
   <version>${mybatis.spring.version}</version>
  </dependency>
  <!-- Mybatis Generator -->
  <dependency>
   <groupId>org.mybatis.generator</groupId>
   <artifactId>mybatis-generator-core</artifactId>
   <version>1.3.2</version>
   <scope>compile</scope>
   <optional>true</optional>
  </dependency>
  <!--分页插件-->
  <dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper</artifactId>
   <version>${pagehelper.version}</version>
  </dependency>
  <!--通用Mapper-->
  <dependency>
   <groupId>tk.mybatis</groupId>
   <artifactId>mapper</artifactId>
   <version>${mapper.version}</version>
  </dependency>
  
  <dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.3.2</version>
   </dependency>
    
 </dependencies>
 <dependencyManagement>
  <dependencies>
   <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-framework-bom</artifactId>
    <version>${spring.version}</version>
    <type>pom</type>
    <scope>import</scope>
   </dependency>
  </dependencies>
 </dependencyManagement>
 <repositories>
  <repository>
   <id>nexus</id>
   <name>local private nexus</name>
   <url>http://maven.oschina.net/content/groups/public/</url>
   <releases>
    <enabled>true</enabled>
   </releases>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>sonatype-nexus-releases</id>
   <name>Sonatype Nexus Releases</name>
   <url>http://oss.sonatype.org/content/repositories/releases</url>
   <releases>
    <enabled>true</enabled>
   </releases>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>sonatype-nexus-snapshots</id>
   <name>Sonatype Nexus Snapshots</name>
   <url>http://oss.sonatype.org/content/repositories/snapshots</url>
   <releases>
    <enabled>false</enabled>
   </releases>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
 </repositories>
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.2</version>
    <configuration>
     <source>1.7</source>
     <target>1.7</target>
    </configuration>
   </plugin>
  </plugins>
 </build>
</project>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
 http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/util 
 http://www.springframework.org/schema/util/spring-util-3.0.xsd
 "> 
 <!-- 配置包扫描 -->
 <context:component-scan base-package="com.krry"></context:component-scan>
  
 <!-- 导入外部资源文件 -->
 <context:property-placeholder location="classpath:jdbc.properties" />

  
 <!-- 配置druid数据源 -->
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
   init-method="init" destroy-method="close">
   <property name="driverClassName" value="${db.driver}" />
   <property name="url" value="${db.url}" />
   <property name="username" value="${db.username}" />
   <property name="password" value="${db.password}" />
 </bean>
 
 <!-- 注册事务管理器 -->
 <bean id="txMgr"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
 </bean>

 <!-- 开启事务注解驱动 -->
 <tx:annotation-driven transaction-manager="txMgr" />
 
 <!-- 配置mybatis的sqlSessionFactory -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="configLocation" value="classpath:mybatis-config.xml"></property>
  <property name="typeAliasesPackage" value="com.krry.entity"/>
  <property name="plugins">
   <array>
    <bean class="com.github.pagehelper.PageInterceptor">
     <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
     <property name="properties">
      <value>

      </value>
     </property>
    </bean>
   </array>
  </property>
 </bean>
 
 <!-- 配置可以整体扫描Mapper的一个扫描器 -->
 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <!--如果有多个报路径,用逗号分开即可 -->
  <property name="basePackage" value="com.krry.mapper"></property>
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
 </bean>
 
</beans>

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="cacheEnabled" value="true" /> 
   <!-- 查询时,关闭关联对象即时加载以提高性能 --> 
  <setting name="lazyLoadingEnabled" value="true" /> 
  <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指    定),不会加载关联表的所有字段,以提高性能 --> 
  <setting name="aggressiveLazyLoading" value="false" /> 
  <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 --> 
  <setting name="multipleResultSetsEnabled" value="true" /> 
  <!-- 允许使用列标签代替列名 --> 
  <setting name="useColumnLabel" value="true" /> 
  <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 --> 
  <setting name="useGeneratedKeys" value="true" /> 
   <!-- 给予被嵌套的resultMap以字段-属性的映射支持 --> 
  <setting name="autoMappingBehavior" value="FULL" /> 
  <!-- 对于批量更新操作缓存SQL以提高性能 --> 
  <setting name="defaultExecutorType" value="BATCH" /> 
   <!-- 数据库超过25000秒仍未响应则超时 --> 
  <setting name="defaultStatementTimeout" value="25" /> 
   <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
 </settings> 
 
 <typeAliases>
  <!--自定义user对象的别名 -->
  <!-- <typeAlias type="com.krry.mybatis.sysmanage.entity.User" alias="user"/> -->
  <!-- 批量定义别名 -->
  <package name="com.krry.entity" />
 </typeAliases> 
</configuration>

springmvc.xml

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:util="http://www.springframework.org/schema/util" 
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.0.xsd
  http://www.springframework.org/schema/util 
  http://www.springframework.org/schema/util/spring-util-3.0.xsd 
  http://www.springframework.org/schema/mvc 
  http://www.springframework.org/schema/mvc/spring-mvc.xsd
  ">
 
  <!-- 开启注解模式驱动 --> 
  <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
  <!-- 开启mvc的注解模式 user 还会注册一个ConversionService 子类FormattingConversionServiceFactoryBean-->
   <mvc:annotation-driven>
   <mvc:message-converters register-defaults="true">
    <bean class="com.krry.core.UTF8StringHttpMessageConverter">
     <property name="supportedMediaTypes">
      <list> 
       <value>text/plain;charset=UTF-8</value> 
       <value>text/html;charset=UTF-8</value> 
      </list> 
     </property>
    </bean> 
    <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
    <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
     <property name="prefixJson" value="false" />
     <property name="objectMapper">
       <bean class="com.fasterxml.jackson.databind.ObjectMapper">
        <!-- 处理responseBody 里面日期类型 --> 
        <property name="dateFormat"> 
         <bean class="java.text.SimpleDateFormat"> 
          <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" /> 
         </bean> 
        </property> 
        <!-- 为null字段时不显示 -->
        <property name="serializationInclusion">
         <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
        </property> 
       </bean> 
     </property>
      <property name="supportedMediaTypes"> 
      <list> 
       <value>application/json;charset=UTF-8</value> 
       <value>application/x-www-form-urlencoded;charset=UTF-8</value> 
      </list> 
     </property>
    </bean>
    </mvc:message-converters> 
  </mvc:annotation-driven>
  
   <!-- 扫包 -->
   <context:component-scan base-package="com.krry.controller"></context:component-scan>  
   <!--对静态资源文件的访问 必须要设置,因为在springmvc的配置中配置了/匹配所有请求,
  此工程所有的请求(.do ,addUser,js/image/css)都会被springmvc解析,
  必须对所有的静态资源文件进行过滤放行 -->
  <!-- 静态资源过滤 下面二选一-->
  <!--<mvc:default-servlet-handler/> -->
  <mvc:resources mapping="/resource/**" location="/resource/" />
 
  <!-- 视图渲染 jsp/freemaker/velocity-->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <!-- 制定页面存放的路径 -->
    <property name="prefix" value="/WEB-INF/pages/"></property>
    <!-- 文件的后缀 -->
    <property name="suffix" value=".jsp"></property>
  </bean> 
</beans>

jdbc.properties 和 log4j.properties 就不用展示了,都差不多的

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
 <display-name>maven_pagehepler</display-name>
 <welcome-file-list>
 <welcome-file>index/index</welcome-file>
 </welcome-file-list>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <listener>
 <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
 </listener>
 <filter>
 <filter-name>encoding</filter-name>
 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
 <init-param>
  <param-name>encoding</param-name>
  <param-value>UTF-8</param-value>
 </init-param>
 </filter>
 <filter-mapping>
 <filter-name>encoding</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
 <servlet>
 <servlet-name>maven_pagehepler</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <init-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:springmvc.xml</param-value>
 </init-param>
 </servlet>
 <servlet-mapping>
 <servlet-name>maven_pagehepler</servlet-name>
 <url-pattern>/index/index</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
 <servlet-name>maven_pagehepler</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

实体类:Country.java

package com.krry.entity;
public class Country { 
 /**
  * 主键
  */
 private Integer id;
 
 /**
  * 名称
  */
 private String countryname;

 /**
  * 代码
  */
 private String countrycode;
 public Country(Integer id, String countryname, String countrycode) {
  this.id = id;
  this.countryname = countryname;
  this.countrycode = countrycode;
 }

 /**
  * 获取主键
  *
  * @return Id - 主键
  */
 public Integer getId() {
  return id;
 }

 /**
  * 设置主键
  *
  * @param id 主键
  */
 public void setId(Integer id) {
  this.id = id;
 }
 
 /**
  * 获取名称
  *
  * @return countryname - 名称
  */
 public String getCountryname() {
  return countryname;
 }

 /**
  * 设置名称
  *
  * @param countryname 名称
  */
 public void setCountryname(String countryname) {
  this.countryname = countryname;
 }

 /**
  * 获取代码
  *
  * @return countrycode - 代码
  */
 public String getCountrycode() {
  return countrycode;
 }

 /**
  * 设置代码
  *
  * @param countrycode 代码
  */
 public void setCountrycode(String countrycode) {
  this.countrycode = countrycode;
 }
}

Params.java

package com.krry.entity;
/**
 * 
 * Params
 * @author krry
 * @version 1.0.0
 *
 */
public class Params {
 private Integer pageSize = 10;
 private Integer pageNo = 0;
 
 public Integer getPageNo() {
  return pageNo;
 }

 public void setPageNo(Integer pageNo) {
  this.pageNo = pageNo;
 }
 
 public Integer getPageSize() {
  return pageSize;
 }

 public void setPageSize(Integer pageSize) {
  this.pageSize = pageSize;
 }
}

持久层:CountryMapper.java

package com.krry.mapper;
import java.util.List;
import com.krry.entity.Country;
/**
 * 
 * Mapper:操作数据库
 * @author krry
 * @version 1.0.0
 *
 */
public interface CountryMapper {

 /**
  * 查询
  * @param params
  * @return
  */
 public List<Country> finds();
 
 /**
  * 计算
  * com.krry.dao.admin 
  * 方法名:countBlogs
  * @author krry 
  * @param params
  * @return int
  * @exception 
  * @since 1.0.0
  */
 public long counts(); 
}

CountryMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.krry.mapper.CountryMapper" > 
 <!-- 分页查询 -->
 <select id="finds" resultType="country">
  SELECT
   id,
   countryname,
   countrycode
  FROM
   country
 </select>
 
 <!-- 查询博客数量 -->
 <select id="counts" resultType="long">
  SELECT
   count(*)
  FROM
   country
 </select> 
</mapper>

业务层接口:

package com.krry.service;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.PageInfo;
import com.krry.entity.Country;
import com.krry.entity.Params;
/**
 * service层:处理业务逻辑(impl里面实现)
 * @author asusaad
 *
 */
public interface ICountryService {
 
 /**
  * 分页查询所有博客
  * @param params 分页参数 pageNo(页码),pageSize(每页查询数目)
  * @return
  */
 public PageInfo<Country> finds(Params params);
 
 /**
  * 计算博客数量
  * @param params
  * @return
  */
 public long counts(); 
}

业务层实现类

package com.krry.service.impl;
import java.util.HashMap;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.krry.entity.Country;
import com.krry.entity.Params;
import com.krry.mapper.CountryMapper;
import com.krry.service.ICountryService;

/**
 * 实现service层接口
 * @author asusaad
 *
 */
@Service
public class CountryService implements ICountryService{

 @Autowired
 private CountryMapper countryMapper;
 
 /**
  * 查询
  */
 public PageInfo<Country> finds(Params params) {
  
  //查询
  int pageNo = params.getPageNo();
  int pageSize = params.getPageSize();
  
  PageHelper.startPage(pageNo, pageSize);
  List<Country> blogs = countryMapper.finds();
  //用PageInfo对结果进行包装
  PageInfo<Country> pageInfo = new PageInfo<Country>(blogs);

  return pageInfo;
  
 }
 
 /**
  * 计算
  * @param params
  * @return
  */
 public long counts(){  
  long couts = countryMapper.counts();  
  return couts;
 }

}

控制层:KrryController.java

package com.krry.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.PageInfo;
import com.krry.entity.Country;
import com.krry.entity.Params;
import com.krry.service.ICountryService;
/**
 * KrryController
 * controller层,作为请求转发
 * @author asusaad
 *
 */
@Controller //表示是多例模式,每个用户返回的web层是不一样的
@RequestMapping("/index")
public class KrryController {
 
 @Autowired
 private ICountryService countryService;
 
 /**
  * 首页,并且分页查询
  * @return
  */
 @RequestMapping("/index")
 public ModelAndView index(Params params){  
  ModelAndView modelAndView = new ModelAndView();
  //一开始第一页,查询10条
  params.setPageNo(1);
  params.setPageSize(10);
  PageInfo<Country> pageInfo = countryService.finds(params);
  
  List<Country> clist = pageInfo.getList();

  //查询数量
  long couts = countryService.counts();

  modelAndView.addObject("clist", clist);
  modelAndView.addObject("couts", couts);
  modelAndView.setViewName("index");
  
  return modelAndView;
 }
 
 /**
  * ajax请求 的 分页查询
  * @param params
  * @return
  */
 @ResponseBody
 @RequestMapping("/loadData")
 public HashMap<String, Object> loadData(Params params){  
  HashMap<String, Object> map = new HashMap<String, Object>();
  PageInfo<Country> pageInfo = countryService.finds(params);
  List<Country> clist = pageInfo.getList();
  map.put("clist", clist);  
  return map;
 }
//  
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持菜鸟教程(cainiaojc.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。