1. 程式人生 > >Spring boot入門(三):SpringBoot整合結合AdminLTE(Freemarker),利用generate自動生成程式碼,利用DataTable和PageHelper進行分頁顯示

Spring boot入門(三):SpringBoot整合結合AdminLTE(Freemarker),利用generate自動生成程式碼,利用DataTable和PageHelper進行分頁顯示

  關於SpringBoot和PageHelper,前篇部落格已經介紹過Spring boot入門(二):Spring boot整合MySql,Mybatis和PageHelper外掛,前篇部落格大致講述了SpringBoot如何整合Mybatis和Pagehelper,但是沒有做出實際的範例,本篇部落格是連線上一篇寫的。通過AdminLTE前端框架,利用DataTable和PageHelper進行分頁顯示,通過對使用者列表的增刪改查操作,演示DataTable和PageHelper的使用。

(1)AdminLTE介紹

  AdminLTE是一個完全響應管理模板。基於Bootstrap3框架,易定製模板。適合多種螢幕解析度,從小型移動裝置到大型桌上型電腦。內建了多個頁面,包括儀表盤、郵箱、日曆、鎖屏、登入及註冊、404錯誤、500錯誤等頁面。具體介紹見官方網站:

https://adminlte.io/,我們可以直接從此網站下載該模板,其外觀如下:

(2)SpringBoot後臺整合AdminLTE

  首先在官網下載AdminLTE模板,然後將此模板的全部檔案拷貝到專案下:

  拷貝後,將AdminLTE檔案進行了拆分,其中base裡面是AdminLTE自帶的所有js包和css檔案,main中是AdminLTE主頁面渲染頁面,index是入口。這麼做的目的:直接將base通過FreeMarker中巨集的形式引入到index入口頁面中,那麼所有的js檔案將一直曾在最底層的頁面下,在後期的其它頁面的開發中,不需要再次引入js包,避免js包混亂。

  啟動專案:

  (3)配置generate

  generate的介紹比較多,此處直接介紹配置的步驟及程式碼

  編寫generatorConfig.xml檔案,並放在templates根目錄下,若放在其它目錄中,則需要在pom.xml中配置路徑,否則,編譯的時候無法通過。具體錯誤:

1 [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project edu: configfile D:\8_Project\learn\edu\src\main\resources\generatorConfig.xml does not exist -> [Help 1]
2 [ERROR] 3 [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch. 4 [ERROR] Re-run Maven using the -X switch to enable full debug logging. 5 [ERROR] 6 [ERROR] For more information about the errors and possible solutions, please read the following articles: 7 [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

generatorConfig.xml的指令碼如下,其中targetProject的路徑需要曾在,否則會報錯,參考https://blog.csdn.net/hh680821/article/details/79051870

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration
 3         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
 4         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 
 6 <generatorConfiguration>
 7    <!-- <properties resource="application.properties"/>-->
 8 
 9     <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
10         <!--屬性配置  -->
11         <property name="beginningDelimiter" value="`"/>
12         <property name="endingDelimiter" value="`"/>
13         <!--去除註釋  -->
14        <commentGenerator>
15             <property name="suppressAllComments" value="true" />
16         </commentGenerator>
17         <!--如果mapper介面需要實現其它介面,那麼需要配置MapperPlugin,value中是實現的介面或類名  -->
18        <plugin type="tk.mybatis.mapper.generator.MapperPlugin">
19             <property name="mappers" value="com.tswc.edu.utils.MyMapper"/>
20         </plugin>
21         <!--一定要放在plugin下面,否則報錯  -->
22         <commentGenerator>
23             <property name="suppressAllComments" value="true" />
24         </commentGenerator>
25         <!--資料庫連線池-->
26         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
27                         connectionURL="jdbc:mysql://localhost:3306/edu"
28                         userId="root"
29                         password="123456">
30         </jdbcConnection>
31         <!--自動生成實體類-->
32         <javaModelGenerator targetPackage="generator" targetProject="src/main/java"/>
33         <!--自動生成map介面-->
34         <sqlMapGenerator targetPackage="generator" targetProject="src/main/java"/>
35         <!--自動生成mybatis的xml檔案-->
36         <javaClientGenerator targetPackage="generator" targetProject="src/main/java"
37                              type="XMLMAPPER"/>
38         <!--資料庫表名,此處如果需要去掉某個自帶函式,需要新增引數-->
39         <!--1,schema:資料庫的schema;
40         2,catalog:資料庫的catalog;
41         3,alias:為資料表設定的別名,如果設定了alias,那麼生成的所有的SELECT SQL語句中,列名會變成:alias_actualColumnName
42         4,domainObjectName:生成的domain類的名字,如果不設定,直接使用表名作為domain類的名字;可以設定為somepck.domainName,那麼會自動把domainName類再放到somepck包裡面;
43         5,enableInsert(預設true):指定是否生成insert語句;
44         6,enableSelectByPrimaryKey(預設true):指定是否生成按照主鍵查詢物件的語句(就是getById或get);
45         7,enableSelectByExample(預設true):MyBatis3Simple為false,指定是否生成動態查詢語句;
46         8,enableUpdateByPrimaryKey(預設true):指定是否生成按照主鍵修改物件的語句(即update);
47         9,enableDeleteByPrimaryKey(預設true):指定是否生成按照主鍵刪除物件的語句(即delete);
48         10,enableDeleteByExample(預設true):MyBatis3Simple為false,指定是否生成動態刪除語句;
49         11,enableCountByExample(預設true):MyBatis3Simple為false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢);
50         12,enableUpdateByExample(預設true):MyBatis3Simple為false,指定是否生成動態修改語句(只修改物件中不為空的屬性);
51         13,modelType:參考context元素的defaultModelType,相當於覆蓋;
52         14,delimitIdentifiers:參考tableName的解釋,注意,預設的delimitIdentifiers是雙引號,如果類似MYSQL這樣的資料庫,使用的是`(反引號,那麼還需要設定context的beginningDelimiter和endingDelimiter屬性)
53         15,delimitAllColumns:設定是否所有生成的SQL中的列名都使用識別符號引起來。預設為false,delimitIdentifiers參考context的屬性
54         注意,table裡面很多引數都是對javaModelGenerator,context等元素的預設屬性的一個複寫;-->
55         <table tableName="t_user">
56             <generatedKey column="id" sqlStatement="Mysql" identity="true"/>
57         </table>
58 
59     </context>
60 </generatorConfiguration>

假設產生此錯誤:

1 [ERROR] Failed to execute goal org.mybatis.generator:mybatis-generator-maven-plugin:1.3.5:generate (default-cli) on project edu: XML Parser Error on line 60: 元素型別為 "context" 的內容必須匹配 "(property*,plugin*,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeResolver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table+)"。 -> [Help 1]
2 [ERROR] 
3 [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
4 [ERROR] Re-run Maven using the -X switch to enable full debug logging.
5 [ERROR] 
6 [ERROR] For more information about the errors and possible solutions, please read the following articles:
7 [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

原因就是:generate中,標籤都是有順序的,此類錯誤就是標籤的順序存在問題

此時,xml檔案以及配置結束,需要在idea中配置啟動操作:mybatis-generator:generate,如圖

(4)DataTable的使用

DataTable是一款簡單易用的分頁外掛,基於JQuery寫的,裡面提供了豐富的分頁引數,主要通過Ajax實現資料的前後端傳輸

首先引入js和css包:

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />

<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

其外,還需要格式化相關提示文字,一般命名為:language.json

 1 {
 2     "sEmptyTable":       "沒有相關資料",
 3     "sInfo":             "從 _START_ 到  _END_ 條記錄 總記錄數為 _TOTAL_ 條",
 4     "sInfoEmpty":        "記錄數為0",
 5     "sInfoFiltered":     "(全部記錄數 _MAX_ 條)",
 6     "sInfoPostFix":      "",
 7     "sInfoThousands":      ",",
 8     "sLengthMenu":       "顯示 _MENU_ 條",
 9     "sLoadingRecords":     "正在載入...",
10     "sProcessing":       "正在獲取資料,請稍候...",
11     "sSearch":           "搜尋",
12     "sZeroRecords":      "沒有您要搜尋的內容",
13     "oPaginate": {
14         "sFirst":        "首頁",
15         "sPrevious":     "上一頁",
16         "sNext":         "下一頁",
17         "sLast":         "尾頁",
18         "sJump":     "跳轉"
19     },
20     "oAria": {
21         "sSortAscending":  ": 以升序排序",
22         "sSortDescending": ": 以降序排序"
23     }
24 }

 

具體的實現方式如下程式碼:

 1 var user_tab;
 2         var user_list_param;
 3         $(function () {
 4             var url="/admin/user/listPage";
 5             user_list_setParm();
 6             user_tab = $('#user_tab').DataTable({
 7                 "fnDrawCallback": function () {
 8                 },
 9                 "dom": '<"top"i>rt<"bottom"flp><"clear">',
10                 //"ordering":false,//是否排序
11                 "processing": true,
12                 "searching": false,
13                 "serverSide": true,   //啟用伺服器端分頁
14                 "order": [[ 5, "asc" ]],//預設排序欄位
15                 "bInfo": true,
16                 "bAutoWidth": false,
17                 "scrollX": true,
18                 "scrollCollapse": false,
19                 /*fixedColumns:   {
20                     leftColumns: 0,
21                     rightColumns: 1
22                 },*/
23                 "language":{"url":"/plugins/datatables/language.json"},
24                 "ajax":{"url":url,"data":user_list_param,"type":"post"},
25                 "columns":[
26                     {"data":"id"},
27                     {"data":null},
28                     {"data":"userName"},
29                     {"data":"password"},
30                     {"data":"trueName"},
31                     {"data":"createTime"},
32                     {"data":"id"}
33                 ],
34                 "columnDefs" : [
35                     {
36                         targets: 0,
37                         data: null,
38                         orderable:false,
39                         render: function (data) {
40                             return '<input type="checkbox" class="userCheckbox" value="'+data+'"/>';
41                         }
42                     },
43                     {
44                         targets: 1,
45                         data: null,
46                         orderable:false,
47                         render: function (data) {
48                             No=No+1;
49                             return No;
50                         }
51                     },
52                     {
53                         "targets" : -1,
54                         "data" : null,
55                         orderable:false,
56                         "render" : function(data) {
57                             var data = "'"+data+"'";
58                             var btn1='<a class="btn btn-xs btn-warning"  target="modal" modal="hg" href=""><i class="fa fa-edit"></i>修改</a> &nbsp;';
59                             var btn2 = '<a class="btn btn-xs btn-danger"  target="modal" modal="hg" onclick="user_list_delete('+data+')"><i class="fa fa-remove"></i>刪除</a> &nbsp;';
60                             return btn1+btn2;
61                         }
62                     }
63                 ]
64             }).on('preXhr.dt', function ( e, settings, data ) {
65                 No=0;
66             }).on('xhr.dt', function(e, settings, json, xhr) {
67             });
68         });

這裡面需要說明的:

a.如果開啟排序,那麼後端接受引數的方式:

@RequestParam(value = "order[0][column]", required = false) Integer orderIndex
@RequestParam(value = "order[0][dir]", required = false) String orderDir
其中orderIndex為排序的欄位,而orderDir為排序的方式(升序或者降序)。orderIndex中是前端table中欄位的列號,所以通暢,還需要在後臺初始化一個數組,然後再陣列中取實際需要排序的欄位,例如:
1   String[] cols = {"", "", "user_name", "password", "true_name", "create_time"};
2   Result<Page<TUser>> result = userService.listPage((start / pageSize) + 1, pageSize,  cols[orderIndex], orderDir);

b.一般在對列表進行了增刪改查後,需要重新重新整理列表,而此時,大多數情況下,想列表保持當前頁面重新整理,那麼需要使用函式

user_tab.draw(false);
其中user_tab為table的JQuery物件,如果不需要保持此頁面,去掉false即可。

c.需要凍結某列的時候,需要使用到fixedColumns函式,可以使用on進行函式回撥,使用dom,進行頁面統計文字的顯示位置"dom": '<"top"i>rt<"bottom"flp><"clear">',

 (5)PageHelper後臺分頁的編寫

 1  public Result<Page<TUser>> listPage(int pageCurrent, int pageSize, String userName, String trueName, String cols, String orderDir) {
 2         Example example = new Example(TUser.class);
 3         Criteria criteria = example.createCriteria();
 4         ExampleUtils.getLikeExample(criteria, "userName", userName);
 5         ExampleUtils.getLikeExample(criteria, "trueName", trueName);
 6         example.setOrderByClause(cols + " " + orderDir);
 7         //example.orderBy(cols+" "+orderDir);
 8         Result<Page<TUser>> result = new Result<Page<TUser>>();
 9         PageHelper.startPage(pageCurrent, pageSize);
10         List<TUser> tUsers = userMapper.selectByExample(example);
11         PageInfo<TUser> pageInfo = new PageInfo<TUser>(tUsers, pageSize);
12         Page<TUser> resultData = new Page<TUser>((int) pageInfo.getTotal(), pageInfo.getPages(), pageCurrent, pageSize, tUsers);
13         result.setResultData(resultData);
14         result.setErrCode(0);
15         result.setStatus(true);
16         return result;
17     }

由於,需要配個DataTable,所以需要重新編寫page類,保證欄位的一致性,這裡就放棄了PageHelper自帶的PageInfo,實際上,這2個類中,欄位型別基本一致,區別不大。

(6).其它具體的程式碼

前端ftl:

  1 <!DOCTYPE html>
  2 <html lang="en">
  3 <head>
  4     <meta charset="UTF-8">
  5     <title>使用者列表</title>
  6 </head>
  7 <body>
  8     <div class="box-body">
  9         <div class="clearfix">
 10             <form class="form-horizontal">
 11                 <input id="user_list_repeatApply" name="user_list_repeatApply" type="reset"  style="display:none;"/>
 12                 <div class="form-group clearfix">
 13                     <label class="col-md-1  control-label">登入名稱</label>
 14                     <div class="col-md-2">
 15                         <input type="text" class="input-sm form-control" id="user_list_user_name" name="user_list_user_name" placeholder="請輸入登入名稱...">
 16                     </div>
 17                     <label class="col-md-1  control-label">使用者名稱</label>
 18                     <div class="col-md-2">
 19                         <input type="text" class="input-sm form-control" id="user_list_true_name" name="user_list_true_name" placeholder="請輸入使用者名稱...">
 20                     </div>
 21                     <button type="button" onclick="user_list_query();" class="btn btn-sm btn-primary" ><i class="fa fa-search"></i>搜尋</button>
 22                     <button type="button" onclick="user_list_add();" class="btn btn-sm btn-success" ><i class="fa fa-square-o"></i>增加</button>
 23                     <button type="button" onclick="user_list_delete('1');" class="btn btn-sm btn-danger" ><i class="fa fa-remove"></i>刪除</button>
 24                     <button  type="button" onclick="user_list_reset();" class="btn btn-sm btn-default">重置</button>
 25                 </div>
 26             </form>
 27         </div>
 28         <table id="user_tab" class="table table-striped table-bordered table-hover">
 29             <thead>
 30                 <tr>
 31                     <th><input type="checkbox" title="全選" /></th>
 32                     <th>序號</th>
 33                     <th>登入名稱</th>
 34                     <th>登入密碼</th>
 35                     <th>使用者名稱</th>
 36                     <th>加入時間</th>
 37                     <th>操作</th>
 38                 </tr>
 39             </thead>
 40         </table>
 41     </div>
 42     <script  type="text/javascript">
 43         var user_tab;
 44         var user_list_param;
 45         $(function () {
 46             var url="/admin/user/listPage";
 47             user_list_setParm();
 48             user_tab = $('#user_tab').DataTable({
 49                 "fnDrawCallback": function () {
 50                 },
 51                 "dom": '<"top"i>rt<"bottom"flp><"clear">',
 52                 //"ordering":false,//是否排序
 53                 "processing": true,
 54                 "searching": false,
 55                 "serverSide": true,   //啟用伺服器端分頁
 56                 "order": [[ 5, "asc" ]],//預設排序欄位
 57                 "bInfo": true,
 58                 "bAutoWidth": false,
 59                 "scrollX": true,
 60                 "scrollCollapse": false,
 61                 /*fixedColumns:   {
 62                     leftColumns: 0,
 63                     rightColumns: 1
 64                 },*/
 65                 "language":{"url":"/plugins/datatables/language.json"},
 66                 "ajax":{"url":url,"data":user_list_param,"type":"post"},
 67                 "columns":[
 68                     {"data":"id"},
 69                     {"data":null},
 70                     {"data":"userName"},
 71                     {"data":"password"},
 72                     {"data":"trueName"},
 73                     {"data":"createTime"},
 74                     {"data":"id"}
 75                 ],
 76                 "columnDefs" : [
 77                     {
 78                         targets: 0,
 79                         data: null,
 80                         orderable:false,
 81                         render: function (data) {
 82                             return '<input type="checkbox" class="userCheckbox" value="'+data+'"/>';
 83                         }
 84                     },
 85                     {
 86                         targets: 1,
 87                         data: null,
 88                         orderable:false,
 89                         render: function (data) {
 90                             No=No+1;
 91                             return No;
 92                         }
 93                     },
 94                     {
 95                         "targets" : -1,
 96                         "data" : null,
 97                         orderable:false,
 98                         "render" : function(data) {
 99                             var data = "'"+data+"'";
100                             var btn1='<a class="btn btn-xs btn-warning"  target="modal" modal="hg" href=""><i class="fa fa-edit"></i>修改</a> &nbsp;';
101                             var btn2 = '<a class="btn btn-xs btn-danger"  target="modal" modal="hg" onclick="user_list_delete('+data+')"><i class="fa fa-remove"></i>刪除</a> &nbsp;';
102                             return btn1+btn2;
103                         }
104                     }
105                 ]
106             }).on('preXhr.dt', function ( e, settings, data ) {
107                 No=0;
108             }).on('xhr.dt', function(e, settings, json, xhr) {
109             });
110         });
111         //搜尋框內容重置
112         function user_list_reset() {
113             $("input[name='user_list_repeatApply']").click();
114         }
115         //增加
116         function user_list_add() {
117 
118         }
119         //刪除
120         function user_list_delete(param) {
121             var href = "/";
122             var title = "<p>警告! 所選取的資料將會被刪除!</p>";
123             var cb;
124             if(param=="1") {
125                 var checkNum = $('input:checkbox[class="userCheckbox"]:checked').length;
126                 var checkVal =[];
127                 if(checkNum==0) {
128                     alertMsg("<p>請選擇資料</p>","warning");
129                     return;
130                 }
131                 $.each($('input:checkbox[class="userCheckbox"]:checked'),function(){
132                     checkVal.push($(this).val());
133                 });
134                 cb = "user_list_delete_data('"+checkVal+"');";
135             } else {
136                 cb = "user_list_delete_one_data('"+param+"');";
137             }
138             $("#smModal").attr("action",href).attr("callback", cb).find(".modal-body").html(title).end().modal("show");
139             //$("#smModal").modal("show");
140         }
141         function user_list_delete_data(checkVal) {
142 
143             var options = {
144                 url:  '/admin/user/delete?checkVal='+checkVal,
145                 type: 'get',
146                 dataType: 'text',
147                 success: function (data) {
148                     if(data>0) {
149                         user_tab.draw(false);
150                         alertMsg("<p>成功刪除"+data+"條記錄</p>","success");
151                     } else {
152                         alertMsg("<p>刪除失敗</p>","danger");
153                     }
154                 }
155             };
156             $.ajax(options);
157         }
158         function user_list_delete_one_data(id) {
159             var options = {
160                 url:  '/admin/user/deleteOne?id='+id,
161                 type: 'get',
162                 dataType: 'text',
163                 success: function (data) {
164                     user_tab.draw(false);
165                     alertMsg("<p>刪除成功</p>","success");
166                 }
167             };
168             $.ajax(options);
169         }
170         //搜尋
171         function user_list_query() {
172             user_list_setParm();
173             user_tab.settings()[0].ajax.data = user_list_param;
174             user_tab.ajax.reload();
175         }
176         //動態拼接引數
177         function user_list_setParm() {
178             var user_list_user_name = $("#user_list_user_name").val();
179             var user_list_true_name = $("#user_list_true_name").val();
180             user_list_param = {
181                 "user_list_user_name" : user_list_user_name,
182                 "user_list_true_name" : user_list_true_name
183             };
184         }
185     </script>
186 </body>
187 </html>
View Code

後臺類:

控制層

 1 package com.tswc.edu.controller;
 2 /**
 3  * @ProjectName: edu
 4  * @Package: com.tswc.edu.controller
 5  * @ClassName: UserContraller
 6  * @Author: DengZeng
 7  * @Description: ${description}
 8  * @Date: 2018/12/15 15:37
 9  * @Version: 1.0
10  */
11 
12 import com.tswc.edu.entity.TUser;
13 import com.tswc.edu.service.UserService;
14 import com.tswc.edu.utils.Page;
15 import com.tswc.edu.utils.PageBean;
16 import com.tswc.edu.utils.Result;
17 import org.springframework.beans.factory.annotation.Autowired;
18 import org.springframework.stereotype.Controller;
19 import org.springframework.web.bind.annotation.RequestMapping;
20 import org.springframework.web.bind.annotation.RequestMethod;
21 import org.springframework.web.bind.annotation.RequestParam;
22 import org.springframework.web.bind.annotation.ResponseBody;
23 
24 /**
25  * 使用者管理
26  *
27  * @author UserContraller
28  * @create 2018-12-15 15:37
29  **/
30 @RequestMapping(value = "/admin/user")
31 @Controller
32 class UserContraller {
33     @Autowired
34     private UserService userService;
35 
36     @RequestMapping(value = "/list")
37     public void list() {
38     }
39 
40     //使用者列表
41     @ResponseBody
42     @RequestMapping(value = "/listPage", method = RequestMethod.POST)
43     public PageBean<TUser> listPage(@RequestParam(value = "start", defaultValue = "1") int start,
44                                     @RequestParam(value = "length", defaultValue = "10") int pageSize,
45                                     @RequestParam(value = "user_list_user_name") String userName,
46                                     @RequestParam(value = "user_list_true_name") String trueName,
47                                     @RequestParam(value = "order[0][column]", required = false) Integer orderIndex,
48                                     @RequestParam(value = "order[0][dir]", required = false) String orderDir) {
49         String[] cols = {"", "", "user_name", "password", "true_name", "create_time"};
50         Result<Page<TUser>> result = userService.listPage((start / pageSize) + 1, pageSize, userName, trueName, cols[orderIndex], orderDir);
51         if (result.isStatus()) {
52             return new PageBean<TUser>(result.getResultData());
53         }
54         return new PageBean<TUser>();
55     }
56 
57     //刪除所選擇的的資料
58     @ResponseBody
59     @RequestMapping(value = "/delete", method = RequestMethod.GET)
60     public int delete(@RequestParam(value = "checkVal") String[] ids) {
61         int result = 0;
62         result = userService.delete(ids);
63         return result;
64     }
65 
66     //刪除一條資料
67     @ResponseBody
68     @RequestMapping(value = "/deleteOne", method = RequestMethod.GET)
69     public void deleteOne(@RequestParam(value = "id") String id) {
70         userService.deleteOne(id);
71     }
72 
73 }
View Code

服務層

 1 package com.tswc.edu.service;
 2 /**
 3  * @ProjectName: edu
 4  * @Package: com.tswc.edu.service
 5  * @ClassName: UserService
 6  * @Author: DengZeng
 7  * @Description: ${description}
 8  * @Date: 2018/12/15 21:25
 9  * @Version: 1.0
10  */
11 
12 import com.github.pagehelper.PageHelper;
13 import com.github.pagehelper.PageInfo;
14 import com.tswc.edu.entity.TUser;
15 import com.tswc.edu.mapper.UserMapper;
16 import com.tswc.edu.utils.ExampleUtils;
17 import com.tswc.edu.utils.Page;
18 import com.tswc.edu.utils.Result;
19 import org.springframework.beans.factory.annotation.Autowired;
20 import org.springframework.stereotype.Service;
21 import tk.mybatis.mapper.entity.Example;
22 import tk.mybatis.mapper.entity.Example.Criteria;
23 
24 import java.util.Arrays;
25 import java.util.List;
26 
27 /**
28  * 使用者管理服務層
29  *
30  * @author UserService
31  * @create 2018-12-15 21:25
32  **/
33 @Service
34 public class UserService {
35     @Autowired
36     private UserMapper userMapper;
37 
38     public Result<Page<TUser>> listPage(int pageCurrent, int pageSize, String userName, String trueName, String cols, String orderDir) {
39         Example example = new Example(TUser.class);
40         Criteria criteria = example.createCriteria();
41         ExampleUtils.getLikeExample(criteria, "userName", userName);
42         ExampleUtils.getLikeExample(criteria, "trueName", trueName);
43         example.setOrderByClause(cols + " " + orderDir);
44         //example.orderBy(cols+" "+orderDir);
45         Result<Page<TUser>> result = new Result<Page<TUser>>();
46         PageHelper.startPage(pageCurrent, pageSize);
47         List<TUser> tUsers = userMapper.selectByExample(example);
48         PageInfo<TUser> pageInfo = new PageInfo<TUser>(tUsers, pageSize);
49         Page<TUser> resultData = new Page<TUser>((int) pageInfo.getTotal(), pageInfo.getPages(), pageCurrent, pageSize, tUsers);
50         result.setResultData(resultData);
51         result.setErrCode(0);
52         result.setStatus(true);
53         return result;
54     }
55 
56     public int delete(String[] ids) {
57         List<String> idList = Arrays.asList(ids);
58         Example example = new Example(TUser.class);
59         Criteria criteria = example.createCriteria();
60         criteria.andIn("id", idList);
61         return userMapper.deleteByExample(example);
62     }
63 
64     public void deleteOne(String id) {
65         userMapper.deleteByPrimaryKey(id);
66     }
67 }
View Code

Mapper介面

1 package com.tswc.edu.mapper;
2 
3 import com.tswc.edu.entity.TUser;
4 import com.tswc.edu.utils.MyMapper;
5 
6 public interface UserMapper extends MyMapper<TUser> {
7 }
View Code

(7).最終效果