Mybatis四種分頁方式


數組分頁

查詢出全部數據,然后再list中截取需要的部分。

mybatis接口

List<Student> queryStudentsByArray();

xml配置文件

 <select id="queryStudentsByArray"  resultMap="studentmapper">
        select * from student
 </select>

service

接口
List<Student> queryStudentsByArray(int currPage, int pageSize);
實現接口
 @Override
    public List<Student> queryStudentsByArray(int currPage, int pageSize) {
        //查詢全部數據
        List<Student> students = studentMapper.queryStudentsByArray();
        //從第幾條數據開始
        int firstIndex = (currPage - 1) * pageSize;
        //到第幾條數據結束
        int lastIndex = currPage * pageSize;
        return students.subList(firstIndex, lastIndex); //直接在list中截取
    }

controller

    @ResponseBody
    @RequestMapping("/student/array/{currPage}/{pageSize}")
    public List<Student> getStudentByArray(@PathVariable("currPage") int currPage, @PathVariable("pageSize") int pageSize) {
        List<Student> student = StuServiceIml.queryStudentsByArray(currPage, pageSize);
        return student;
    }

sql分頁

mybatis接口

List<Student> queryStudentsBySql(Map<String,Object> data);

xml文件

<select id="queryStudentsBySql" parameterType="map" resultMap="studentmapper">
        select * from student limit #{currIndex} , #{pageSize}
</select>

service

接口
List<Student> queryStudentsBySql(int currPage, int pageSize);
實現類
public List<Student> queryStudentsBySql(int currPage, int pageSize) {
        Map<String, Object> data = new HashedMap();
        data.put("currIndex", (currPage-1)*pageSize);
        data.put("pageSize", pageSize);
        return studentMapper.queryStudentsBySql(data);
    }

springjdbctemplete寫分頁語句

攔截器分頁

創建攔截器,攔截mybatis接口方法id以ByPage結束的語句

package com.autumn.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Connection;
import java.util.Map;
import java.util.Properties;

/**
 * @Intercepts 說明是一個攔截器
 * @Signature 攔截器的簽名
 * type 攔截的類型 四大對象之一( Executor,ResultSetHandler,ParameterHandler,StatementHandler)
 * method 攔截的方法
 * args 參數,高版本需要加個Integer.class參數,不然會報錯
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class MyPageInterceptor implements Interceptor {

    //每頁顯示的條目數
    private int pageSize;
    //當前現實的頁數
    private int currPage;
    //數據庫類型
    private String dbType;


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //獲取StatementHandler,默認是RoutingStatementHandler
        StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        //獲取statementHandler包裝類
        MetaObject MetaObjectHandler = SystemMetaObject.forObject(statementHandler);

        //分離代理對象鏈
        while (MetaObjectHandler.hasGetter("h")) {
            Object obj = MetaObjectHandler.getValue("h");
            MetaObjectHandler = SystemMetaObject.forObject(obj);
        }

        while (MetaObjectHandler.hasGetter("target")) {
            Object obj = MetaObjectHandler.getValue("target");
            MetaObjectHandler = SystemMetaObject.forObject(obj);
        }

        //獲取連接對象
        //Connection connection = (Connection) invocation.getArgs()[0];


        //object.getValue("delegate");  獲取StatementHandler的實現類

        //獲取查詢接口映射的相關信息
        MappedStatement mappedStatement = (MappedStatement) MetaObjectHandler.getValue("delegate.mappedStatement");
        String mapId = mappedStatement.getId();

        //statementHandler.getBoundSql().getParameterObject();

        //攔截以.ByPage結尾的請求,分頁功能的統一實現
        if (mapId.matches(".+ByPage$")) {
            //獲取進行數據庫操作時管理參數的handler
            ParameterHandler parameterHandler = (ParameterHandler) MetaObjectHandler.getValue("delegate.parameterHandler");
            //獲取請求時的參數
            Map<String, Object> paraObject = (Map<String, Object>) parameterHandler.getParameterObject();
            //也可以這樣獲取
            //paraObject = (Map<String, Object>) statementHandler.getBoundSql().getParameterObject();

            //參數名稱和在service中設置到map中的名稱一致
            currPage = (int) paraObject.get("currPage");
            pageSize = (int) paraObject.get("pageSize");

            String sql = (String) MetaObjectHandler.getValue("delegate.boundSql.sql");
            //也可以通過statementHandler直接獲取
            //sql = statementHandler.getBoundSql().getSql();

            //構建分頁功能的sql語句
            String limitSql;
            sql = sql.trim();
            limitSql = sql + " limit " + (currPage - 1) * pageSize + "," + pageSize;

            //將構建完成的分頁sql語句賦值個體'delegate.boundSql.sql',偷天換日
            MetaObjectHandler.setValue("delegate.boundSql.sql", limitSql);
        }
        //調用原對象的方法,進入責任鏈的下一級
        return invocation.proceed();
    }


    //獲取代理對象
    @Override
    public Object plugin(Object o) {
        //生成object對象的動態代理對象
        return Plugin.wrap(o, this);
    }

    //設置代理對象的參數
    @Override
    public void setProperties(Properties properties) {
        //如果項目中分頁的pageSize是統一的,也可以在這里統一配置和獲取,這樣就不用每次請求都傳遞pageSize參數了。參數是在配置攔截器時配置的。
        String limit1 = properties.getProperty("limit", "10");
        this.pageSize = Integer.valueOf(limit1);
        this.dbType = properties.getProperty("dbType", "mysql");
    }
}

 配置文件SqlMapConfig.xml

<configuration>

    <plugins>
        <plugin interceptor="com.autumn.interceptor.MyPageInterceptor">
            <property name="limit" value="10"/>
            <property name="dbType" value="mysql"/>
        </plugin>
    </plugins>

</configuration>

mybatis配置

<!--接口-->
List<AccountExt> getAllBookByPage(@Param("currPage")Integer pageNo,@Param("pageSize")Integer pageSize);
<!--xml配置文件-->
  <sql id="getAllBooksql" >
    acc.id, acc.cateCode, cate_name, user_id,u.name as user_name, money, remark, time
  </sql>
  <select id="getAllBook" resultType="com.autumn.pojo.AccountExt" >
    select
    <include refid="getAllBooksql" />
    from account as acc
  </select>

service

    public List<AccountExt> getAllBookByPage(String pageNo,String pageSize) {
        return accountMapper.getAllBookByPage(Integer.parseInt(pageNo),Integer.parseInt(pageSize));
    }

controller

    @RequestMapping("/getAllBook")
    @ResponseBody
    public Page getAllBook(String pageNo,String pageSize,HttpServletRequest request,HttpServletResponse response){
        pageNo=pageNo==null?"1":pageNo;   //當前頁碼
        pageSize=pageSize==null?"5":pageSize;   //頁面大小
        //獲取當前頁數據
        List<AccountExt> list = bookService.getAllBookByPage(pageNo,pageSize);
        //獲取總數據大小
        int totals = bookService.getAllBook();
        //封裝返回結果
        Page page = new Page();
        page.setTotal(totals+"");
        page.setRows(list);
        return page;
    }

Page實體類

package com.autumn.pojo;

import java.util.List;

/**
 * Created by Autumn on 2018/6/21.
 */
public class Page {
    private String pageNo = null;
    private String pageSize = null;
    private String total = null;
    private List rows = null;

    public String getTotal() {
        return total;
    }

    public void setTotal(String total) {
        this.total = total;
    }

    public List getRows() {
        return rows;
    }

    public void setRows(List rows) {
        this.rows = rows;
    }

    public String getPageNo() {
        return pageNo;
    }

    public void setPageNo(String pageNo) {
        this.pageNo = pageNo;
    }

    public String getPageSize() {
        return pageSize;
    }

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

}

前端

bootstrap-table接受數據格式

{
  "total": 3,
  "rows": [
    {
      "id": 0,
      "name": "Item 0",
      "price": "$0"
    },
    {
      "id": 1,
      "name": "Item 1",
      "price": "$1"
    }
  ]
}

boostrap-table用法

        var $table = $('#table');
        $table.bootstrapTable({
        url: "/${appName}/manager/bookController/getAllBook",
        method: 'post',
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        pagination: true, //分頁
        sidePagination: "server", //服務端處理分頁
        pageList: [5, 10, 25],
        pageSize: 5,
        pageNumber:1,
        //toolbar:"#tb",
        singleSelect: false,
        queryParamsType : "limit",
        queryParams: function queryParams(params) {   //設置查詢參數
          var param = {
            pageNo: params.offset/params.limit+1,  //offset為數據開始索引,轉換為顯示當前頁
            pageSize: params.limit  //頁面大小
          };
          console.info(params);   //查看參數是什么
          console.info(param);   //查看自定義的參數
          return param;
        },
        cache: false,
        //data-locale: "zh-CN", //表格漢化
        //search: true, //顯示搜索框
        columns: [
                {
                    checkbox: true
                },
                {
                    title: '消費類型',
                    field: 'cate_name',
                    valign: 'middle'
                },
                {
                    title: '消費金額',
                    field: 'money',
                    valign: 'middle',
                    formatter:function(value,row,index){
                        if(!isNaN(value)){   //是數字
                            return value/100;
                        }
                    }
                },
                {
                    title: '備注',
                    field: 'remark',
                    valign: 'middle'
                },
                {
                    title: '消費時間',
                    field: 'time',
                    valign: 'middle'
                },
                {
                    title: '操作',
                    field: '',
                    formatter:function(value,row,index){
                        var f = '<a href="#" class="btn btn-gmtx-define1" onclick="delBook(\''+ row.id +'\')">刪除</a> ';
                        return f;
                       }
                }
            ]
          });
      });

RowBounds分頁

數據量小時,RowBounds不失為一種好辦法。但是數據量大時,實現攔截器就很有必要了。

mybatis接口加入RowBounds參數

public List<UserBean> queryUsersByPage(String userName, RowBounds rowBounds);

service

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.SUPPORTS)
    public List<RoleBean> queryRolesByPage(String roleName, int start, int limit) {
        return roleDao.queryRolesByPage(roleName, new RowBounds(start, limit));
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM