關於SpringBoot和PageHelper,前篇博客已經介紹過Spring boot入門(二):Spring boot集成MySql,Mybatis和PageHelper插件,前篇博客大體講述了SpringBoot如何集成Mybatis和Pagehelper,可是沒有作出實際的範例,本篇博客是鏈接上一篇寫的。經過AdminLTE前端框架,利用DataTable和PageHelper進行分頁顯示,經過對用戶列表的增刪改查操做,演示DataTable和PageHelper的使用。javascript
(1)AdminLTE介紹css
AdminLTE是一個徹底響應管理模板。基於Bootstrap3框架,易定製模板。適合多種屏幕分辨率,從小型移動設備到大型臺式機。內置了多個頁面,包括儀表盤、郵箱、日曆、鎖屏、登陸及註冊、404錯誤、500錯誤等頁面。具體介紹見官方網站:https://adminlte.io/,咱們能夠直接今後網站下載該模板,其外觀以下:html
(2)SpringBoot後臺集成AdminLTE前端
首先在官網下載AdminLTE模板,而後將此模板的所有文件拷貝到項目下:java
拷貝後,將AdminLTE文件進行了拆分,其中base裏面是AdminLTE自帶的全部js包和css文件,main中是AdminLTE主頁面渲染頁面,index是入口。這麼作的目的:直接將base經過FreeMarker中宏的形式引入到index入口頁面中,那麼全部的js文件將一直曾在最底層的頁面下,在後期的其它頁面的開發中,不須要再次引入js包,避免js包混亂。mysql
啓動項目:jquery
(3)配置generategit
generate的介紹比較多,此處直接介紹配置的步驟及代碼github
增長依賴jar包,在build下增長web
1 <plugin> 2 <groupId>org.mybatis.generator</groupId> 3 <artifactId>mybatis-generator-maven-plugin</artifactId> 4 <version>1.3.7</version> 5 <dependencies> 6 <dependency> 7 <groupId>mysql</groupId> 8 <artifactId>mysql-connector-java</artifactId> 9 <version>${mysql-connector-java.version}</version> 10 </dependency> 11 <dependency> 12 <groupId>org.mybatis.generator</groupId> 13 <artifactId>mybatis-generator-core</artifactId> 14 <version>1.3.7</version> 15 </dependency> 16 <dependency> 17 <groupId>tk.mybatis</groupId> 18 <artifactId>mapper</artifactId> 19 <version>${mapper.version}</version> 20 </dependency> 21 </dependencies> 22 <executions> 23 <execution> 24 <id>Generate MyBatis Artifacts</id> 25 <phase>package</phase> 26 <goals> 27 <goal>generate</goal> 28 </goals> 29 </execution> 30 </executions> 31 <configuration> 32 <!--容許移動生成的文件 --> 33 <verbose>true</verbose> 34 <!-- 是否覆蓋 --> 35 <overwrite>true</overwrite> 36 <!-- 自動生成的配置 --> 37 <!-- <configurationFile>generatorConfig.xml</configurationFile>--> 38 </configuration> 39 </plugin>
編寫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> '; 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> '; 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> '; 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> '; 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>
後臺類:
控制層
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 }
服務層
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 }
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 }
(7).最終效果