1. 程式人生 > >Layui+Springboot+Mybatis+Pagehelper實現條件分頁查詢

Layui+Springboot+Mybatis+Pagehelper實現條件分頁查詢

分頁查詢是Web專案中非常重要的一項,Mybatis對於條件分頁查詢有其天然優勢,動態sql的靈活運用使得sql語句變得簡潔,在本文中,使用Pagehelper分頁外掛並結合Mybatis逆向出的實體進行條件查詢。

首先,匯入Pagehelper依賴

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

在前臺進行查詢的時候,會有許多的條件傳過來,先看個例子:此為controller程式碼

/**
     * 所有使用者列表
     */
    @ResponseBody
    @RequestMapping("/list")
    public Result<SysUser> userlist(Result<SysUser> result, SysUser example)
    {   PageHelper.startPage(result.getPage(), result.getLimit());//傳入起始頁與頁數大小
result.setExample(example);//設定條件 Result<SysUser> all = sysUserService.getAll(result);//帶條件查詢 PageInfo page = new PageInfo(all.getData());//將使用者資料封裝到PageInfo 中 result.setCode("0");//設定成功程式碼 result.setCount(page.getPageSize());//設定資料數量 return result; }

Result為封裝所有返回資料的實體,包含layui框架所需要的欄位,程式碼如下:

public class Result<T> implements Serializable {
    int page;//起始頁
    int limit;//頁數大小
    int count;//資料數量
    String code;//程式碼
    String msg;//資訊
    List<T> data;//返回資料
    T example;//任何型別條件
    }

接下來是sysUserService中的程式碼:

public Result<SysUser> getAll(Result<SysUser> result) {
        SysUserExample example = new SysUserExample();//逆向實體類
        SysUserExample.Criteria criteria =  example.createCriteria();
        SysUser ex = result.getExample();
        setCriteria(criteria,ex);//判斷是否有該條件,並進行條件查詢
        List<SysUser> sysUsers = sysUserDao.selectByExample(example);//根據條件查詢,該方法為Mybatis逆向出的
        result.setData(sysUsers);//設定資料
        return result;
    }
private void setCriteria(SysUserExample.Criteria criteria, SysUser example) {
        if (!StringUtils.isEmpty(example.getUserId().toString()))
            criteria.andUserIdEqualTo(example.getUserId());
        if (!StringUtils.isEmpty(example.getUsername().toString()))
            criteria.andUsernameEqualTo(example.getUsername());
    }

以上兩段程式碼將前端傳來的資訊進行查詢,接下來就是前端頁面的傳送與展示:

<!DOCTYPE html>
<html>
<head>
<title>管理員列表</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <link rel="stylesheet" href="/statics/plugins/layui/css/layui.css" media="all"/>
    <link rel="stylesheet" href="/statics/plugins/font-awesome/css/font-awesome.min.css" media="all"/>
    <link rel="stylesheet" href="/statics/src/css/app.css" media="all"/>
    <link rel="stylesheet" href="/statics/src/css/themes/default.css" media="all" id="skin" kit-skin/>
    <script src="/statics/plugins/layui/layui.js"></script>
</head>
<body>
<div id="rrapp" v-cloak>
    <div v-show="showList">
        <table id="jqGrid"></table>
        <div id="jqGridPager"></div>
    </div>
</div>
<script>
    layui.use('table', function () {
        var $ = layui.$;
        var table = layui.table, form = layui.form;
        table.render({
            elem: '#jqGrid',
            url: '/sys/user/list',
            cellMinWidth: 80,
            cols: [
                [{
                    checkbox: true,
                    fixed: true
                }, {
                    field: 'userId',
                    title: '員工編號',
                }, {
                    field: 'username',
                    title: '使用者名稱',
                }, {
                    field: 'email',
                    title: '郵箱',
                }, {
                    field: 'mobile',
                    title: '手機號',
                },  {
                    field: 'createTime',
                    title: '建立時間',
                }]
            ],
            id: 'reloadId',
            page: true
        });
        var active = {
            reload: function () {
                var s_name = $('#s_name');
                table.reload('reloadId', {
                    page: {
                        curr: 1 //重新從第 1 頁開始
                    },
                    where: {
                        username: s_name.val(),
                    }
                });
            },
            getCheckData: function () { //獲取選中資料
                var checkStatus = table.checkStatus('reloadId');
                var data = checkStatus.data;
                $.post({
                    dataType: 'json',
                    contentType: 'application/json',
                    url: "/staff/deletes",
                    data: JSON.stringify(data),
                    success: function (result) {
                        if (result.code == 0) {
                            layer.msg('已刪除!', {icon: 1, time: 1000});
                            table.reload('reloadId');
                        } else {
                            layer.msg(result.result, {icon: 6, time: 1000});
                        }
                    },
                    error: function () {
                        layer.msg('網路繁忙!', {icon: 6, time: 1000});
                    }
                });
            }
        }; 
    });
        );
    }


</script>
</body>
</html>

該程式碼中url為向控制器傳送請求的路徑,active中的s_name為向後端傳送的條件,條件可以為多個,在本例中,沒有設定條件,因此,控制器接收到的條件example屬性均為null。layui向控制器傳送請求預設起始頁為1,頁數大小為10,控制器返回json資料並交給layui顯示。