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

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

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

Mybatis分页插件 demo 项目地址:https://gitee.com/free/Mybatis_PageHelper

我这里使用 maven 工程实现:

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

1 <dependency>
2     <groupId>com.github.pagehelper</groupId>
3     <artifactId>pagehelper</artifactId>
4     <version>5.0.0</version>
5 </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 语句按照一般查询写法,不用写分页:

1 <!-- 分页查询 -->
2     <select id="finds" resultType="country">
3         SELECT
4             id,
5             countryname,
6             countrycode
7         FROM
8             country
9     </select>

mapper 层接口:

1    /**
2      * 查询
3      * @param params
4      * @return
5      */
6     public List<Country> finds();

service 业务层接口:

1    /**
2      * 分页查询
3      * @param params 分页参数 pageNo(页码),pageSize(每页查询数目)
4      * @return
5      */
6     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 返回到控制层

 1 /**
 2      * 查询
 3      */
 4     public PageInfo<Country> finds(Params params) {
 5         
 6         //查询
 7         int pageNo = params.getPageNo();
 8         int pageSize = params.getPageSize();
 9         
10         PageHelper.startPage(pageNo, pageSize);
11         List<Country> blogs = countryMapper.finds();
12         //用PageInfo对结果进行包装
13         PageInfo<Country> pageInfo = new PageInfo<Country>(blogs);
14 
15         return pageInfo;
16         
17     }

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

List<Country> clist = pageInfo.getList(); 再将 clist  放进作用域,在前台页面利用<c:forEach></c:forEach>可循环获得分页数据

 1 /**
 2      * 首页,并且分页查询
 3      * @return
 4      */
 5     @RequestMapping("/index")
 6     public ModelAndView index(Params params){
 7         
 8         ModelAndView modelAndView = new ModelAndView();
 9         //一开始第一页,查询10条
10         params.setPageNo(1);
11         params.setPageSize(10);
12         PageInfo<Country> pageInfo = countryService.finds(params);
13         
14         List<Country> clist = pageInfo.getList();
15 
16         //查询数量
17         long couts = countryService.counts();
18 
19         modelAndView.addObject("clist", clist);
20         modelAndView.addObject("couts", couts);
21         modelAndView.setViewName("index");
22         
23         return modelAndView;
24     }

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

pom.xml

  1 <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
  2          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3     <modelVersion>4.0.0</modelVersion>
  4     <groupId>com.krry</groupId>
  5     <artifactId>maven_pagehepler_ora</artifactId>
  6     <packaging>war</packaging>
  7     <version>1.0-SNAPSHOT</version>
  8     <name>maven_pagehepler_ora</name>
  9     <url>http://maven.apache.org</url>
 10 
 11     <properties>
 12         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 13         <!--  MyBatis Generator  -->
 14         <!--  Java接口和实体类  -->
 15         <targetJavaProject>${basedir}/src/main/java</targetJavaProject>
 16         <targetMapperPackage>com.isea533.mybatis.mapper</targetMapperPackage>
 17         <targetModelPackage>com.isea533.mybatis.model</targetModelPackage>
 18         <!--  XML生成路径  -->
 19         <targetResourcesProject>${basedir}/src/main/resources</targetResourcesProject>
 20         <targetXMLPackage>mapper</targetXMLPackage>
 21         <!--  编译jdk版本  -->
 22         <jdk.version>1.6</jdk.version>
 23         <!--  依赖版本  -->
 24         <mybatis.version>3.3.1</mybatis.version>
 25         <mapper.version>3.3.6</mapper.version>
 26         <pagehelper.version>5.0.0</pagehelper.version>
 27         <mysql.version>5.1.29</mysql.version>
 28         <spring.version>4.1.2.RELEASE</spring.version>
 29         <mybatis.spring.version>1.2.4</mybatis.spring.version>
 30     </properties>
 31 
 32     <dependencies>
 33         <dependency>
 34             <groupId>junit</groupId>
 35             <artifactId>junit</artifactId>
 36             <version>4.11</version>
 37             <scope>test</scope>
 38         </dependency>
 39         <dependency>
 40             <groupId>log4j</groupId>
 41             <artifactId>log4j</artifactId>
 42             <version>1.2.17</version>
 43         </dependency>
 44 
 45         <!--web-->
 46         <dependency>
 47             <groupId>javax.servlet</groupId>
 48             <artifactId>servlet-api</artifactId>
 49             <version>2.5</version>
 50             <scope>provided</scope>
 51         </dependency>
 52         <dependency>
 53             <groupId>javax.servlet.jsp</groupId>
 54             <artifactId>jsp-api</artifactId>
 55             <version>2.1</version>
 56             <scope>provided</scope>
 57         </dependency>
 58         <dependency>
 59             <groupId>javax.servlet</groupId>
 60             <artifactId>jstl</artifactId>
 61             <version>1.2</version>
 62         </dependency>
 63         <dependency>
 64             <groupId>javax.ws.rs</groupId>
 65             <artifactId>javax.ws.rs-api</artifactId>
 66             <version>2.0</version>
 67         </dependency>
 68         <dependency>
 69             <groupId>javax.websocket</groupId>
 70             <artifactId>javax.websocket-api</artifactId>
 71             <version>1.0</version>
 72         </dependency>
 73         <dependency>
 74             <groupId>javax.annotation</groupId>
 75             <artifactId>javax.annotation-api</artifactId>
 76             <version>1.2</version>
 77         </dependency>
 78         <dependency>
 79             <groupId>javax.transaction</groupId>
 80             <artifactId>javax.transaction-api</artifactId>
 81             <version>1.2</version>
 82         </dependency>
 83 
 84         <!--Spring-->
 85         <dependency>
 86             <groupId>org.springframework</groupId>
 87             <artifactId>spring-context</artifactId>
 88         </dependency>
 89         <dependency>
 90             <groupId>org.springframework</groupId>
 91             <artifactId>spring-orm</artifactId>
 92         </dependency>
 93         <dependency>
 94             <groupId>org.springframework</groupId>
 95             <artifactId>spring-oxm</artifactId>
 96         </dependency>
 97         <dependency>
 98             <groupId>org.springframework</groupId>
 99             <artifactId>spring-jdbc</artifactId>
100         </dependency>
101         <dependency>
102             <groupId>org.springframework</groupId>
103             <artifactId>spring-tx</artifactId>
104         </dependency>
105         <dependency>
106             <groupId>org.springframework</groupId>
107             <artifactId>spring-web</artifactId>
108         </dependency>
109         <dependency>
110             <groupId>org.springframework</groupId>
111             <artifactId>spring-webmvc</artifactId>
112         </dependency>
113         <dependency>
114             <groupId>org.springframework</groupId>
115             <artifactId>spring-aop</artifactId>
116         </dependency>
117         <dependency>
118             <groupId>org.springframework</groupId>
119             <artifactId>spring-test</artifactId>
120         </dependency>
121 
122         <!--spring-oxm依赖-->
123         <dependency>
124             <groupId>org.codehaus.castor</groupId>
125             <artifactId>castor-xml</artifactId>
126             <version>1.3.3</version>
127         </dependency>
128         <!--spring-json依赖-->
129         <dependency>
130             <groupId>com.fasterxml.jackson.core</groupId>
131             <artifactId>jackson-databind</artifactId>
132             <version>2.4.2</version>
133         </dependency>
134         <dependency>
135             <groupId>com.fasterxml.jackson.dataformat</groupId>
136             <artifactId>jackson-dataformat-xml</artifactId>
137             <version>2.4.2</version>
138         </dependency>
139         <!--spring-aop依赖-->
140         <dependency>
141             <groupId>org.aspectj</groupId>
142             <artifactId>aspectjweaver</artifactId>
143             <version>1.8.2</version>
144         </dependency>
145 
146         <!--上传文件-->
147         <dependency>
148             <groupId>commons-fileupload</groupId>
149             <artifactId>commons-fileupload</artifactId>
150             <version>1.3.1</version>
151         </dependency>
152 
153         <!--mysql-->
154         <dependency>
155             <groupId>mysql</groupId>
156             <artifactId>mysql-connector-java</artifactId>
157             <version>${mysql.version}</version>
158         </dependency>
159         
160         <!--druid-->
161         <dependency>
162             <groupId>com.alibaba</groupId>
163             <artifactId>druid</artifactId>
164             <version>1.0.11</version>
165         </dependency>
166 
167         <!--Mybatis-->
168         <dependency>
169             <groupId>org.mybatis</groupId>
170             <artifactId>mybatis</artifactId>
171             <version>${mybatis.version}</version>
172         </dependency>
173         <dependency>
174             <groupId>org.mybatis</groupId>
175             <artifactId>mybatis-spring</artifactId>
176             <version>${mybatis.spring.version}</version>
177         </dependency>
178         <!-- Mybatis Generator -->
179         <dependency>
180             <groupId>org.mybatis.generator</groupId>
181             <artifactId>mybatis-generator-core</artifactId>
182             <version>1.3.2</version>
183             <scope>compile</scope>
184             <optional>true</optional>
185         </dependency>
186         <!--分页插件-->
187         <dependency>
188             <groupId>com.github.pagehelper</groupId>
189             <artifactId>pagehelper</artifactId>
190             <version>${pagehelper.version}</version>
191         </dependency>
192         <!--通用Mapper-->
193         <dependency>
194             <groupId>tk.mybatis</groupId>
195             <artifactId>mapper</artifactId>
196             <version>${mapper.version}</version>
197         </dependency>
198         
199         <dependency>
200             <groupId>org.apache.commons</groupId>
201             <artifactId>commons-lang3</artifactId>
202             <version>3.3.2</version>
203           </dependency>
204         
205         
206     </dependencies>
207     <dependencyManagement>
208         <dependencies>
209             <dependency>
210                 <groupId>org.springframework</groupId>
211                 <artifactId>spring-framework-bom</artifactId>
212                 <version>${spring.version}</version>
213                 <type>pom</type>
214                 <scope>import</scope>
215             </dependency>
216         </dependencies>
217     </dependencyManagement>
218     <repositories>
219         <repository>
220             <id>nexus</id>
221             <name>local private nexus</name>
222             <url>http://maven.oschina.net/content/groups/public/</url>
223             <releases>
224                 <enabled>true</enabled>
225             </releases>
226             <snapshots>
227                 <enabled>false</enabled>
228             </snapshots>
229         </repository>
230         <repository>
231             <id>sonatype-nexus-releases</id>
232             <name>Sonatype Nexus Releases</name>
233             <url>http://oss.sonatype.org/content/repositories/releases</url>
234             <releases>
235                 <enabled>true</enabled>
236             </releases>
237             <snapshots>
238                 <enabled>false</enabled>
239             </snapshots>
240         </repository>
241         <repository>
242             <id>sonatype-nexus-snapshots</id>
243             <name>Sonatype Nexus Snapshots</name>
244             <url>http://oss.sonatype.org/content/repositories/snapshots</url>
245             <releases>
246                 <enabled>false</enabled>
247             </releases>
248             <snapshots>
249                 <enabled>true</enabled>
250             </snapshots>
251         </repository>
252     </repositories>
253     <build>
254         <plugins>
255             <plugin>
256                 <groupId>org.apache.maven.plugins</groupId>
257                 <artifactId>maven-compiler-plugin</artifactId>
258                 <version>3.2</version>
259                 <configuration>
260                     <source>1.7</source>
261                     <target>1.7</target>
262                 </configuration>
263             </plugin>
264         </plugins>
265     </build>
266 </project>

applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 4     xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 5     xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans   
 7   http://www.springframework.org/schema/beans/spring-beans.xsd  
 8   http://www.springframework.org/schema/aop   
 9   http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
10   http://www.springframework.org/schema/tx   
11   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
12   http://www.springframework.org/schema/context   
13   http://www.springframework.org/schema/context/spring-context-3.0.xsd
14   http://www.springframework.org/schema/util   
15   http://www.springframework.org/schema/util/spring-util-3.0.xsd
16   ">
17     
18     
19     <!-- 配置包扫描 -->
20     <context:component-scan base-package="com.krry"></context:component-scan>
21         
22     <!-- 导入外部资源文件 -->
23     <context:property-placeholder location="classpath:jdbc.properties" />
24 
25         
26     <!-- 配置druid数据源 -->
27     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
28           init-method="init" destroy-method="close">
29           <property name="driverClassName" value="${db.driver}" />
30           <property name="url" value="${db.url}" />
31           <property name="username" value="${db.username}" />
32           <property name="password" value="${db.password}" />
33     </bean>
34     
35     <!-- 注册事务管理器 -->
36     <bean id="txMgr"
37         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
38         <property name="dataSource" ref="dataSource"></property>
39     </bean>
40 
41     <!-- 开启事务注解驱动 -->
42     <tx:annotation-driven transaction-manager="txMgr" />
43     
44     <!-- 配置mybatis的sqlSessionFactory -->
45     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
46         <property name="dataSource" ref="dataSource"/>
47         <property name="configLocation" value="classpath:mybatis-config.xml"></property>
48         <property name="typeAliasesPackage" value="com.krry.entity"/>
49         <property name="plugins">
50             <array>
51                 <bean class="com.github.pagehelper.PageInterceptor">
52                     <!-- 这里的几个配置主要演示如何使用,如果不理解,一定要去掉下面的配置 -->
53                     <property name="properties">
54                         <value>
55 
56                         </value>
57                     </property>
58                 </bean>
59             </array>
60         </property>
61     </bean>
62     
63     <!-- 配置可以整体扫描Mapper的一个扫描器 -->
64     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
65         <!--如果有多个报路径,用逗号分开即可  -->
66         <property name="basePackage" value="com.krry.mapper"></property>
67         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
68     </bean>
69     
70 </beans>

mybatis-config.xml

 1 <?xml version="1.0" encoding="UTF-8"?>  
 2 <!DOCTYPE configuration   
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">  
 5 
 6 <configuration> 
 7     <settings>  
 8          <!-- 全局映射器启用缓存 -->  
 9         <setting name="cacheEnabled" value="true" />  
10          <!-- 查询时,关闭关联对象即时加载以提高性能 -->  
11         <setting name="lazyLoadingEnabled" value="true" />  
12         <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指              定),不会加载关联表的所有字段,以提高性能 -->  
13         <setting name="aggressiveLazyLoading" value="false" />  
14         <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->  
15         <setting name="multipleResultSetsEnabled" value="true" />  
16         <!-- 允许使用列标签代替列名 -->  
17         <setting name="useColumnLabel" value="true" />  
18         <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->  
19         <setting name="useGeneratedKeys" value="true" />  
20          <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->  
21         <setting name="autoMappingBehavior" value="FULL" />  
22         <!-- 对于批量更新操作缓存SQL以提高性能  -->  
23         <setting name="defaultExecutorType" value="BATCH" />  
24          <!-- 数据库超过25000秒仍未响应则超时 -->  
25         <setting name="defaultStatementTimeout" value="25" />  
26          <setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
27     </settings>  
28     
29     <typeAliases>
30         <!--自定义user对象的别名  -->
31         <!-- <typeAlias type="com.krry.mybatis.sysmanage.entity.User" alias="user"/> -->
32         <!-- 批量定义别名 -->
33         <package name="com.krry.entity" />
34     </typeAliases>
35      
36 </configuration>  

springmvc.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 4     xmlns:p="http://www.springframework.org/schema/p"
 5     xmlns:context="http://www.springframework.org/schema/context"
 6     xmlns:util="http://www.springframework.org/schema/util" 
 7     xmlns:mvc="http://www.springframework.org/schema/mvc"
 8     xsi:schemaLocation="http://www.springframework.org/schema/beans
 9        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
10        http://www.springframework.org/schema/context 
11        http://www.springframework.org/schema/context/spring-context-3.0.xsd
12        http://www.springframework.org/schema/util 
13        http://www.springframework.org/schema/util/spring-util-3.0.xsd 
14        http://www.springframework.org/schema/mvc 
15        http://www.springframework.org/schema/mvc/spring-mvc.xsd
16       ">
17    
18       <!-- 开启注解模式驱动 -->    
19         <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
20         <!-- 开启mvc的注解模式 user 还会注册一个ConversionService 子类FormattingConversionServiceFactoryBean-->
21          <mvc:annotation-driven>
22             <mvc:message-converters register-defaults="true">
23                 <bean class="com.krry.core.UTF8StringHttpMessageConverter">
24                     <property name="supportedMediaTypes">
25                         <list>  
26                             <value>text/plain;charset=UTF-8</value>  
27                             <value>text/html;charset=UTF-8</value>  
28                         </list>  
29                     </property>
30                 </bean> 
31                 <bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
32                 <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> 
33                 <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
34                     <property name="prefixJson" value="false" />
35                     <property name="objectMapper">
36                          <bean class="com.fasterxml.jackson.databind.ObjectMapper">
37                                <!-- 处理responseBody 里面日期类型 --> 
38                                <property name="dateFormat">  
39                                    <bean class="java.text.SimpleDateFormat">  
40                                        <constructor-arg type="java.lang.String" value="yyyy-MM-dd HH:mm:ss" />  
41                                    </bean>  
42                                </property> 
43                                <!-- 为null字段时不显示 -->
44                                <property name="serializationInclusion">
45                                    <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
46                                </property> 
47                            </bean>  
48                     </property>
49                      <property name="supportedMediaTypes">  
50                         <list>  
51                             <value>application/json;charset=UTF-8</value>  
52                             <value>application/x-www-form-urlencoded;charset=UTF-8</value>  
53                         </list>  
54                     </property>
55                 </bean>
56                 </mvc:message-converters> 
57         </mvc:annotation-driven>
58       
59           
60          <!-- 扫包 -->
61          <context:component-scan base-package="com.krry.controller"></context:component-scan>
62          
63          <!--对静态资源文件的访问  必须要设置,因为在springmvc的配置中配置了/匹配所有请求,
64         此工程所有的请求(.do ,addUser,js/image/css)都会被springmvc解析,
65         必须对所有的静态资源文件进行过滤放行 -->
66       <!-- 静态资源过滤  下面二选一-->
67       <!--<mvc:default-servlet-handler/> -->
68       <mvc:resources mapping="/resource/**" location="/resource/" />
69      
70        
71    
72        <!-- 视图渲染 jsp/freemaker/velocity-->
73        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
74                <!-- 制定页面存放的路径 -->
75                <property name="prefix" value="/WEB-INF/pages/"></property>
76                <!-- 文件的后缀 -->
77                <property name="suffix" value=".jsp"></property>
78        </bean> 
79     
80 </beans>

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

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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">
 3   <display-name>maven_pagehepler</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index/index</welcome-file>
 6   </welcome-file-list>
 7   <context-param>
 8     <param-name>contextConfigLocation</param-name>
 9     <param-value>classpath:applicationContext.xml</param-value>
10   </context-param>
11   <listener>
12     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
13   </listener>
14   <listener>
15     <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
16   </listener>
17   <filter>
18     <filter-name>encoding</filter-name>
19     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
20     <init-param>
21       <param-name>encoding</param-name>
22       <param-value>UTF-8</param-value>
23     </init-param>
24   </filter>
25   <filter-mapping>
26     <filter-name>encoding</filter-name>
27     <url-pattern>/*</url-pattern>
28   </filter-mapping>
29   <servlet>
30     <servlet-name>maven_pagehepler</servlet-name>
31     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
32     <init-param>
33       <param-name>contextConfigLocation</param-name>
34       <param-value>classpath:springmvc.xml</param-value>
35     </init-param>
36   </servlet>
37   <servlet-mapping>
38     <servlet-name>maven_pagehepler</servlet-name>
39     <url-pattern>/index/index</url-pattern>
40   </servlet-mapping>
41   <servlet-mapping>
42     <servlet-name>maven_pagehepler</servlet-name>
43     <url-pattern>/</url-pattern>
44   </servlet-mapping>
45 </web-app>

实体类:Country.java

 1 package com.krry.entity;
 2 
 3 public class Country {
 4     
 5     
 6     /**
 7      * 主键
 8      */
 9     private Integer id;
10     
11     /**
12      * 名称
13      */
14     private String countryname;
15 
16     /**
17      * 代码
18      */
19     private String countrycode;
20     
21     
22     
23     public Country(Integer id, String countryname, String countrycode) {
24         this.id = id;
25         this.countryname = countryname;
26         this.countrycode = countrycode;
27     }
28 
29     /**
30      * 获取主键
31      *
32      * @return Id - 主键
33      */
34     public Integer getId() {
35         return id;
36     }
37 
38     /**
39      * 设置主键
40      *
41      * @param id 主键
42      */
43     public void setId(Integer id) {
44         this.id = id;
45     }
46     
47     /**
48      * 获取名称
49      *
50      * @return countryname - 名称
51      */
52     public String getCountryname() {
53         return countryname;
54     }
55 
56     /**
57      * 设置名称
58      *
59      * @param countryname 名称
60      */
61     public void setCountryname(String countryname) {
62         this.countryname = countryname;
63     }
64 
65     /**
66      * 获取代码
67      *
68      * @return countrycode - 代码
69      */
70     public String getCountrycode() {
71         return countrycode;
72     }
73 
74     /**
75      * 设置代码
76      *
77      * @param countrycode 代码
78      */
79     public void setCountrycode(String countrycode) {
80         this.countrycode = countrycode;
81     }
82 }

Params.java

 1 package com.krry.entity;
 2 
 3 /**
 4  * 
 5  * Params
 6  * @author krry
 7  * @version 1.0.0
 8  *
 9  */
10 public class Params {
11 
12     private Integer pageSize = 10;
13     private Integer pageNo = 0;
14     
15 
16     public Integer getPageNo() {
17         return pageNo;
18     }
19 
20     public void setPageNo(Integer pageNo) {
21         this.pageNo = pageNo;
22     }
23     
24     public Integer getPageSize() {
25         return pageSize;
26     }
27 
28     public void setPageSize(Integer pageSize) {
29         this.pageSize = pageSize;
30     }
31 
32 }

持久层:CountryMapper.java

 1 package com.krry.mapper;
 2 
 3 import java.util.List;
 4 
 5 import com.krry.entity.Country;
 6 
 7 /**
 8  * 
 9  * Mapper:操作数据库
10  * @author krry
11  * @version 1.0.0
12  *
13  */
14 public interface CountryMapper {
15 
16     /**
17      * 查询
18      * @param params
19      * @return
20      */
21     public List<Country> finds();
22     
23     /**
24      * 计算
25      * com.krry.dao.admin 
26      * 方法名:countBlogs
27      * @author krry 
28      * @param params
29      * @return int
30      * @exception 
31      * @since  1.0.0
32      */
33     public long counts();
34     
35     
36 }

CountryMapper.xml

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 3 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 4 
 5 <mapper namespace="com.krry.mapper.CountryMapper" >
 6     
 7     <!-- 分页查询 -->
 8     <select id="finds" resultType="country">
 9         SELECT
10             id,
11             countryname,
12             countrycode
13         FROM
14             country
15     </select>
16     
17     <!-- 查询博客数量 -->
18     <select id="counts" resultType="long">
19         SELECT
20             count(*)
21         FROM
22             country
23     </select>
24     
25     
26 </mapper>

业务层接口:

 1 package com.krry.service;
 2 
 3 import java.util.HashMap;
 4 import java.util.List;
 5 
 6 import javax.servlet.http.HttpServletRequest;
 7 
 8 import org.apache.ibatis.annotations.Param;
 9 
10 import com.github.pagehelper.PageInfo;
11 import com.krry.entity.Country;
12 import com.krry.entity.Params;
13 
14 /**
15  * service层:处理业务逻辑(impl里面实现)
16  * @author asusaad
17  *
18  */
19 public interface ICountryService {
20     
21     /**
22      * 分页查询所有博客
23      * @param params  分页参数 pageNo(页码),pageSize(每页查询数目)
24      * @return
25      */
26     public PageInfo<Country> finds(Params params);
27     
28     /**
29      * 计算博客数量
30      * @param params
31      * @return
32      */
33     public long counts();
34     
35 }

业务层实现类

 1 package com.krry.service.impl;
 2 
 3 import java.util.HashMap;
 4 import java.util.List;
 5 
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 import com.github.pagehelper.PageHelper;
11 import com.github.pagehelper.PageInfo;
12 import com.krry.entity.Country;
13 import com.krry.entity.Params;
14 import com.krry.mapper.CountryMapper;
15 import com.krry.service.ICountryService;
16 
17 /**
18  * 实现service层接口
19  * @author asusaad
20  *
21  */
22 @Service
23 public class CountryService implements ICountryService{
24 
25     @Autowired
26     private CountryMapper countryMapper;
27     
28     /**
29      * 查询
30      */
31     public PageInfo<Country> finds(Params params) {
32         
33         //查询
34         int pageNo = params.getPageNo();
35         int pageSize = params.getPageSize();
36         
37         PageHelper.startPage(pageNo, pageSize);
38         List<Country> blogs = countryMapper.finds();
39         //用PageInfo对结果进行包装
40         PageInfo<Country> pageInfo = new PageInfo<Country>(blogs);
41 
42         return pageInfo;
43         
44     }
45     
46     /**
47      * 计算
48      * @param params
49      * @return
50      */
51     public long counts(){
52         
53         long couts = countryMapper.counts();
54         
55         return couts;
56     }
57     
58     
59 
60 }

控制层:KrryController.java

 1 package com.krry.controller;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.List;
 6 
 7 import org.junit.Test;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.stereotype.Controller;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.ResponseBody;
12 import org.springframework.web.servlet.ModelAndView;
13 
14 import com.github.pagehelper.PageInfo;
15 import com.krry.entity.Country;
16 import com.krry.entity.Params;
17 import com.krry.service.ICountryService;
18 
19 /**
20  * KrryController
21  * controller层,作为请求转发
22  * @author asusaad
23  *
24  */
25 @Controller  //表示是多例模式,每个用户返回的web层是不一样的
26 @RequestMapping("/index")
27 public class KrryController {
28     
29     @Autowired
30     private ICountryService countryService;
31     
32     /**
33      * 首页,并且分页查询
34      * @return
35      */
36     @RequestMapping("/index")
37     public ModelAndView index(Params params){
38         
39         ModelAndView modelAndView = new ModelAndView();
40         //一开始第一页,查询10条
41         params.setPageNo(1);
42         params.setPageSize(10);
43         PageInfo<Country> pageInfo = countryService.finds(params);
44         
45         List<Country> clist = pageInfo.getList();
46 
47         //查询数量
48         long couts = countryService.counts();
49 
50         modelAndView.addObject("clist", clist);
51         modelAndView.addObject("couts", couts);
52         modelAndView.setViewName("index");
53         
54         return modelAndView;
55     }
56     
57     /**
58      * ajax请求 的 分页查询
59      * @param params
60      * @return
61      */
62     @ResponseBody
63     @RequestMapping("/loadData")
64     public HashMap<String, Object> loadData(Params params){
65         
66         
67         HashMap<String, Object> map = new HashMap<String, Object>();
68         PageInfo<Country> pageInfo = countryService.finds(params);
69         List<Country> clist = pageInfo.getList();
70         map.put("clist", clist);
71         
72         return map;
73     }
74 //    
75     
76 }

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏Hadoop实操

如何使用Flume采集Kafka数据写入Kudu

1.6K2
来自专栏nice_每一天

spring+spring mvc+mybatis 实现主从数据库配置

@DataSourceChange(slave = true)只对service(业务)层起作用。

1563
来自专栏用户2442861的专栏

Spring+Mybatis+SpringMVC后台与前台分页展示实例(附工程)

      林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka

1562
来自专栏开发技术

spring-boot-2.0.3之quartz集成,不是你想的那样哦!

    晚上回家,爸妈正在吵架,见我回来就都不说话了,看见我妈坐在那里瞪着我爸,我就问老爸“你干什么了惹我妈生这么大气?”  我爸说“没有什么啊,倒是你,这么大...

2333
来自专栏Java3y

从零开始写项目第一篇【搭建环境】

使用Maven搭建SSM环境 SSM需要的基础jar包有哪些??整理一下: c3p0数据连接池 springMVC的JSON springAOP springC...

53510
来自专栏何俊林

结合Android源码分析总结单例模式的几种实现方式

本文为付祥投稿,主要是结合Android源码分析总结单例模式的几种实现方式。 谈起设计模式估计大家都不会陌生,一个项目中至少会用到其中的一种模式,今天要说的主角...

4768
来自专栏码匠的流水账

聊聊eureka的delta配置

eureka-client-1.8.8-sources.jar!/com/netflix/discovery/DiscoveryClient.java

961
来自专栏jeremy的技术点滴

SSM项目脚手架

4864
来自专栏小灰灰

RabbitMQ基础教程之Spring&JavaConfig使用篇

2407
来自专栏.NET开发者社区

一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](二)

在本系列第一篇《一步一步创建ASP.NET MVC5程序[Repository+Autofac+Automapper+SqlSugar](一)》中,我为大家介绍...

29610

扫码关注云+社区

领取腾讯云代金券