Home Database Mysql Tutorial [DB][MyBatis]利用mybatis-paginator实现分页

[DB][MyBatis]利用mybatis-paginator实现分页

Jun 10, 2016 pm 03:12 PM
mybatis

利用mybatis-paginator实现分页 1、mybatis-paginator简介 mybatis-paginator是gethub上的一个开源项目、用于java后台获取分页数据、该开源项目还提供一个列表组件(mmgrid)用于前端展示。 该开源项目地址:https://github.com/miemiedev 2、该开源项目的使

 

利用mybatis-paginator实现分页

 

1、mybatis-paginator简介

mybatis-paginator是gethub上的一个开源项目、用于java后台获取分页数据、该开源项目还提供一个列表组件(mmgrid)用于前端展示。

该开源项目地址:https://github.com/miemiedev

 

2、该开源项目的使用说明:

Maven中加入依赖:

<dependencies>  
  ...  
    <dependency>  
        <groupId>com.github.miemiedev</groupId>  
        <artifactId>mybatis-paginator</artifactId>  
        <version>1.2.10</version>  
    </dependency>  
  ...  
</dependencies>
Copy after login


Mybatis配置文件添加分页插件:

<?xmlversionxmlversion="1.0"encoding="UTF-8"?>  
<!DOCTYPE configuration  PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN"  
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">  
<configuration>  
    <plugins>  
        <plugin interceptor="com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor">  
            <propertynamepropertyname="dialectClass"value="com.github.miemiedev.mybatis.paginator.
            dialect.OracleDialect"/>  
        </plugin>  
     </plugins>  
</configuration>
Copy after login


创建一个查询,内容可以是任何Mybatis表达式,包括foreach和if等:

<selectidselectid="findByCity"resultType="map">  
    select * from TEST_USER where city = #{city};  
</select>
Copy after login


Dao中的方法或许是这样(用接口也是类似):

public List findByCity(String city, PageBounds pageBounds){
    Mapparams =new HashMap();
    params.put("city",city);
    returngetSqlSession().selectList("db.table.user.findByCity", params, pageBounds);
}
Copy after login


调用方式(分页加多列排序):

int page = 1; //页号
int pageSize = 20; //每页数据条数
String sortString = "age.asc,gender.desc";//如果你想排序的话逗号分隔可以排序多列

PageBounds pageBounds = newPageBounds(page, pageSize , Order.formString(sortString));

List list = findByCity("BeiJing",pageBounds);

//获得结果集条总数
PageList pageList = (PageList)list;
System.out.println("totalCount: "+ pageList.getPaginator().getTotalCount());
Copy after login

PageList类是继承于ArrayList的,这样Dao中就不用为了专门分页再多写一个方法。

使用PageBounds这个对象来控制结果的输出,常用的使用方式一般都可以通过构造函数来配置。

new PageBounds();//默认构造函数不提供分页,返回ArrayList
new PageBounds(int limit);//取TOPN操作,返回ArrayList
new PageBounds(Order... order);//只排序不分页,返回ArrayList
new PageBounds(int page, int limit);//默认分页,返回PageList
new PageBounds(int page, int limit, Order... order);//分页加排序,返回PageList
new PageBounds(int page, int limit, Listorders,boolean containsTotalCount);
//使用containsTotalCount来决定查不查询totalCount,即返回ArrayList还是PageList
Copy after login


=========================================

如果用的是Spring MVC的话可以把JSON的配置写成这样:

<mvc:annotation-driven>  
    <mvc:message-converters register-defaults="true">  
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">  
            <constructor-argvalueconstructor-argvalue="UTF-8"/>          
        </bean>  
   
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
             <property name="objectMapper">  
             <bean class="com.github.miemiedev.mybatis.paginator.jackson2.PageListJsonMapper"/>  
             </property>  
         </bean>  
     </mvc:message-converters>  
 </mvc:annotation-driven>
Copy after login

那么在Controller就可以这样用了:


@ResponseBody
@RequestMapping(value ="/findByCity.json")
public List findByCity(@RequestParam String city,
                 @RequestParam(required =false,defaultValue ="1") intpage,
                 @RequestParam(required =false,defaultValue ="30") intlimit,
                 @RequestParam(required =false) String sort,
                 @RequestParam(required =false) String dir) {
 
    return userService.findByCity(city, newPageBounds(page, limit, Order.create(sort,dir)));
}
Copy after login




然后序列化后的JSON字符串就会变成这样的:

{
    "items":[
        {"NAME":"xiaoma","AGE":30,"GENDER":1,"ID":3,"CITY":"BeiJing"},
        {"NAME":"xiaoli","AGE":30,"SCORE":85,"GENDER":1,"ID":1,"CITY":"BeiJing"},
        {"NAME":"xiaowang","AGE":30,"SCORE":92,"GENDER":0,"ID":2,"CITY":"BeiJing"},
        {"NAME":"xiaoshao","AGE":30,"SCORE":99,"GENDER":0,"ID":4,"CITY":"BeiJing"}
    ],

    "slider": [1, 2, 3, 4, 5, 6, 7],
    "hasPrePage":false,
    "startRow": 1,
    "offset": 0,
    "lastPage":false,
    "prePage": 1,
    "hasNextPage":true,
    "nextPage": 2,
    "endRow": 30,
    "totalCount": 40351,
    "firstPage":true,
    "totalPages": 1346,
    "limit": 30,
    "page": 1
}
Copy after login

=========================================

在SpringMVC中使用JSTL的话可以参考一下步骤(懒人用法)

在Spring配置文件中加入拦截器,或则参考拦截器实现定义自己的拦截器

<mvc:interceptors>  
    <mvc:interceptor>  
        <mvc:mapping path="/**"/>  
       <bean class="com.github.miemiedev.mybatis.paginator.springmvc.PageListAttrHandlerInterceptor"/>  
    </mvc:interceptor>  
</mvc:interceptors>
Copy after login

然后Controller方法可以这样写

@RequestMapping(value ="/userView.action")
public ModelAndView userView(@RequestParam String city,
                 @RequestParam(required =false,defaultValue ="1")intpage,
                 @RequestParam(required =false,defaultValue ="30")intlimit,
                 @RequestParam(required =false) String sort,
                 @RequestParam(required =false) String dir) {
    List users = userService.findByCity(city,newPageBounds(page, limit, Order.create(sort,dir)));
    returnnewModelAndView("account/user","users", users);
}
Copy after login

JSP中就可以这样用了,拦截器会将PageList分拆添加Paginator属性,默认命名规则为"原属性名称"+"Paginator"

<table>  
    <c:forEach items="${users}"var="user">  
        <tr>  
            <td>${user[&#39;ID&#39;]}</td>  
            <td>${user[&#39;NAME&#39;]}</td>  
            <td>${user[&#39;AGE&#39;]}</td>  
        </tr>  
    </c:forEach>  
</table>  
  
上一页: ${usersPaginator.prePage}   
当前页: ${usersPaginator.page}   
下一页: ${usersPaginator.nextPage}   
总页数: ${usersPaginator.totalPages}   
总条数: ${usersPaginator.totalCount}   
  
  
更多属性参考Paginator类提供的方法
Copy after login

=========================================

如果用如下方法设置pageBounds,当前这个查询就可以用两个线程同时查询list和totalCount了

pageBounds.setAsyncTotalCount(true);
Copy after login


如果所有的分页查询都是用异步的方式查询list和totalCount,可以在插件配置加入asyncTotalCount属性

<plugin interceptor="com.github.miemiedev.mybatis.paginator.OffsetLimitInterceptor">  
    <property name="dialectClass" value="com.github.miemiedev.mybatis.paginator.dialect.OracleDialect"/>  
    <property name="asyncTotalCount" value="true"/>  
</plugin>
Copy after login

但是你仍然可以用下面代码强制让这个查询不用异步

pageBounds.setAsyncTotalCount(false);
Copy after login

当然需要注意的是,只要你用到了异步查询,由于里面使用了线程池,所以在使用时就要加入清理监听器,以便在停止服务时关闭线程池。需要在web.xml中加入

<listener>  
    <listener-class>com.github.miemiedev.mybatis.paginator.CleanupMybatisPaginatorListener</listener-class>  
</listener>
Copy after login

以上就是[DB][MyBatis]利用mybatis的内容,更多相关内容请关注PHP中文网(www.php.cn)!




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

iBatis vs. MyBatis: Which one is better for you? iBatis vs. MyBatis: Which one is better for you? Feb 19, 2024 pm 04:38 PM

iBatis vs. MyBatis: Which should you choose? Introduction: With the rapid development of the Java language, many persistence frameworks have emerged. iBatis and MyBatis are two popular persistence frameworks, both of which provide a simple and efficient data access solution. This article will introduce the features and advantages of iBatis and MyBatis, and give some specific code examples to help you choose the appropriate framework. Introduction to iBatis: iBatis is an open source persistence framework

Various ways to implement batch deletion operations in MyBatis Various ways to implement batch deletion operations in MyBatis Feb 19, 2024 pm 07:31 PM

Several ways to implement batch deletion statements in MyBatis require specific code examples. In recent years, due to the increasing amount of data, batch operations have become an important part of database operations. In actual development, we often need to delete records in the database in batches. This article will focus on several ways to implement batch delete statements in MyBatis and provide corresponding code examples. Use the foreach tag to implement batch deletion. MyBatis provides the foreach tag, which can easily traverse a set.

Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Detailed explanation of the Set tag function in MyBatis dynamic SQL tags Feb 26, 2024 pm 07:48 PM

Interpretation of MyBatis dynamic SQL tags: Detailed explanation of Set tag usage MyBatis is an excellent persistence layer framework. It provides a wealth of dynamic SQL tags and can flexibly construct database operation statements. Among them, the Set tag is used to generate the SET clause in the UPDATE statement, which is very commonly used in update operations. This article will explain in detail the usage of the Set tag in MyBatis and demonstrate its functionality through specific code examples. What is Set tag Set tag is used in MyBati

Comparative analysis of the functions and performance of JPA and MyBatis Comparative analysis of the functions and performance of JPA and MyBatis Feb 19, 2024 pm 05:43 PM

JPA and MyBatis: Function and Performance Comparative Analysis Introduction: In Java development, the persistence framework plays a very important role. Common persistence frameworks include JPA (JavaPersistenceAPI) and MyBatis. This article will conduct a comparative analysis of the functions and performance of the two frameworks and provide specific code examples. 1. Function comparison: JPA: JPA is part of JavaEE and provides an object-oriented data persistence solution. It is passed annotation or X

Detailed explanation of how to use MyBatis batch delete statements Detailed explanation of how to use MyBatis batch delete statements Feb 20, 2024 am 08:31 AM

Detailed explanation of how to use MyBatis batch delete statements requires specific code examples. Introduction: MyBatis is an excellent persistence layer framework that provides rich SQL operation functions. In actual project development, we often encounter situations where data needs to be deleted in batches. This article will introduce in detail how to use MyBatis batch delete statements, and attach specific code examples. Usage scenario: When deleting a large amount of data in the database, it is inefficient to execute the delete statements one by one. At this point, you can use the batch deletion function of MyBatis

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? Feb 23, 2024 pm 08:13 PM

Detailed explanation of MyBatis first-level cache: How to improve data access efficiency? During the development process, efficient data access has always been one of the focuses of programmers. For persistence layer frameworks like MyBatis, caching is one of the key methods to improve data access efficiency. MyBatis provides two caching mechanisms: first-level cache and second-level cache. The first-level cache is enabled by default. This article will introduce the mechanism of MyBatis first-level cache in detail and provide specific code examples to help readers better understand

MyBatis Generator configuration parameter interpretation and best practices MyBatis Generator configuration parameter interpretation and best practices Feb 23, 2024 am 09:51 AM

MyBatisGenerator is a code generation tool officially provided by MyBatis, which can help developers quickly generate JavaBeans, Mapper interfaces and XML mapping files that conform to the database table structure. In the process of using MyBatisGenerator for code generation, the setting of configuration parameters is crucial. This article will start from the perspective of configuration parameters and deeply explore the functions of MyBatisGenerator.

Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Analyze the caching mechanism of MyBatis: compare the characteristics and usage of first-level cache and second-level cache Feb 25, 2024 pm 12:30 PM

Analysis of MyBatis' caching mechanism: The difference and application of first-level cache and second-level cache In the MyBatis framework, caching is a very important feature that can effectively improve the performance of database operations. Among them, first-level cache and second-level cache are two commonly used caching mechanisms in MyBatis. This article will analyze the differences and applications of first-level cache and second-level cache in detail, and provide specific code examples to illustrate. 1. Level 1 Cache Level 1 cache is also called local cache. It is enabled by default and cannot be turned off. The first level cache is SqlSes

See all articles