主要參考另外兩篇博文,這裡表示感謝
參考一(mybatisplus3.x分頁) : https://www.jianshu.com/p/2ec9337dc2b0
參考二(mybatisplus2.x更新3.x) : https://my.oschina.net/u/241218/blog/1838534
mybatisplus2.x 和 mybatisplus3.x 變化比較大, 資料查詢的時候注意版本, 可以避依賴沖突.
0.建立springboot web項目(打包模式一定要用war包 ,否則報錯找不到模版,目前還不知道原因)
1. demo項目環境 springboot-2.1.1 + mybatisplus3.0.6 + velocity2.0 + jdk1.8 + idea
2. application.yml
server:
port:8080servlet:
context-path: /maven #項目名稱
spring:
profiles:
active: local #@spring.active@ #預設使用本地配置檔案
mvc:static-path-pattern: /static
public static voidmain(String[] args) {//自定義需要填充的字段
List tableFillList = new ArrayList<>();
tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE));
AutoGenerator mpg= newAutoGenerator();//選擇 freemarker 引擎,預設 Veloctiy//mpg.setTemplateEngine(new FreemarkerTemplateEngine());//全局配置
GlobalConfig gc = newGlobalConfig();
gc.setOutputDir("F:\\idea-maven\\maven\\src\\main\\java");
gc.setFileOverride(true);
gc.setActiveRecord(true);//不需要ActiveRecord特性的請改為false
gc.setEnableCache(false);//XML 二級緩存
gc.setBaseResultMap(true);//XML ResultMap
gc.setBaseColumnList(true);//XML columList//gc.setKotlin(true);//是否生成 kotlin 代碼
gc.setAuthor("Hcl");//自定義檔案命名,注意 %s 會自動填充表實體屬性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setControllerName("%sController");
mpg.setGlobalConfig(gc);//資料源配置
DataSourceConfig dsc = newDataSourceConfig();
dsc.setDbType(DbType.MYSQL);dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&serverTimezone=Hongkong");
mpg.setDataSource(dsc);//政策配置
StrategyConfig strategy = newStrategyConfig();//strategy.setCapitalMode(true);//全局大寫命名 ORACLE 注意//strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });//此處可以修改為您的表字首
strategy.setNaming(NamingStrategy.underline_to_camel);//表名生成政策//strategy.setInclude(new String[]{"app_certificate"});//需要生成的表,注釋掉生成全部表//strategy.setExclude(new String[]{"test"});//排除生成的表//自定義實體父類//strategy.setSuperEntityClass("com.baomidou.demo.TestEntity");//自定義實體,公共字段//strategy.setSuperEntityColumns(new String[] { "test_id", "age" });//自定義 mapper 父類//strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");//自定義 service 父類//strategy.setSuperServiceClass("com.baomidou.demo.TestService");//自定義 service 實作類父類//strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");//自定義 controller 父類//strategy.setSuperControllerClass("com.baomidou.demo.TestController");//【實體】是否生成字段常量(預設 false)//public static final String ID = "test_id";//strategy.setEntityColumnConstant(true);//【實體】是否為建構者模型(預設 false)//public User setName(String name) {this.name = name; return this;}//strategy.setEntityBuilderModel(true);
strategy.setTableFillList(tableFillList);
mpg.setStrategy(strategy);//包配置
PackageConfig pc = newPackageConfig();
pc.setParent("com.dofun");
pc.setController("controller");
pc.setXml("mapper");
mpg.setPackageInfo(pc);//注入自定義配置,可以在 VM 中使用 cfg.abc 【可無】 ${cfg.abc}
InjectionConfig cfg = newInjectionConfig() {
@Overridepublic voidinitMap() {
Map map = new HashMap();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");this.setMap(map);
}
};//自定義 xxListIndex.html 生成
List focList = new ArrayList();
focList.add(new FileOutConfig("/templates/list.html.vm") {
@OverridepublicString outputFile(TableInfo tableInfo) {//自定義輸入檔案名稱
return "F:/idea-maven/maven/src/main/resources/static/" + tableInfo.getEntityName() + "ListIndex.html";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);//關閉預設 xml 生成,調整生成 至 根目錄
//自定義模闆配置,可以 copy 源碼 mybatis-plus/src/main/resources/templates 下面内容修改,//放置自己項目的 src/main/resources/templates 目錄下, 預設名稱一下可以不配置,也可以自定義模闆名稱
TemplateConfig tc = newTemplateConfig();
tc.setController("/templates/controller.java.vm");
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setEntity("/templates/entity.java.vm");
tc.setMapper("/templates/mapper.java.vm");
tc.setXml("/templates/mapper.xml.vm");//如上任何一個子產品如果設定 空 OR Null 将不生成該子產品。
mpg.setTemplate(tc);//執行生成
mpg.execute();//列印注入設定【可無】
System.err.println(mpg.getCfg().getMap().get("abc"));
}
}
packagecom.dofun.common;importjava.io.Serializable;importjava.util.List;public class DatatablesJSON implementsSerializable {//目前頁面
private intdraw;//總頁數
private longrecordsTotal;private longrecordsFiltered;//響應狀态 預設false
private Boolean success = false;//響應消息
privateString error;public ListgetData() {returndata;
}public void setData(Listdata) {this.data =data;
}//存放的資料
private Listdata;public intgetDraw() {returndraw;
}public void setDraw(intdraw) {this.draw =draw;
}public longgetRecordsTotal() {returnrecordsTotal;
}public void setRecordsTotal(longrecordsTotal) {this.recordsTotal =recordsTotal;
}public longgetRecordsFiltered() {returnrecordsFiltered;
}public void setRecordsFiltered(longrecordsFiltered) {this.recordsFiltered =recordsFiltered;
}publicBoolean getSuccess() {returnsuccess;
}public voidsetSuccess(Boolean success) {this.success =success;
}publicString getError() {returnerror;
}public voidsetError(String error) {this.error =error;
}
}
packagecom.dofun.common;importjava.io.Serializable;
public class JSONResult implementsSerializable {//響應狀态 預設false
private Boolean success = false;//響應消息
privateString message;//存放的資料
privateT data;publicJSONResult() {super();
}publicBoolean getSuccess() {returnsuccess;
}public voidsetSuccess(Boolean success) {this.success =success;
}publicString getMessage() {returnmessage;
}public voidsetMessage(String message) {this.message =message;
}publicT getData() {returndata;
}public voidsetData(T data) {this.data =data;
}
}
5. controller 模版 controller.java.vm
package ${package.Controller};importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RequestMethod;
#if(${restControllerStyle})importorg.springframework.web.bind.annotation.RestController;
#else
importorg.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})import${superControllerClassPackage};
#endimportorg.springframework.beans.factory.annotation.Autowired;importcom.baomidou.mybatisplus.core.conditions.query.QueryWrapper;importcom.baomidou.mybatisplus.extension.plugins.pagination.Page;import ${package.Service}.${table.serviceName};importcom.dofun.common.DatatablesJSON;importcom.dofun.common.JSONResult;import ${package.Entity}.${entity};importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;#if(${restControllerStyle})
@RestController
#[email protected]
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${superControllerClass})public class ${table.controllerName} extends${superControllerClass} {
#else
public class${table.controllerName} {
#endprivate final Logger logger=LoggerFactory.getLogger(${table.controllerName}.class);
@Autowiredpublic${table.serviceName} ${table.entityPath}Service;@RequestMapping(value= "/get${entity}List", method =RequestMethod.POST)public Object get${entity}List(${entity} param,@RequestParam(value = "draw", defaultValue = "0") Integer draw,
@RequestParam(value= "length") Integer length,
@RequestParam(value= "start") Integer start){
DatatablesJSON resJson=new DatatablesJSON<>();try{
## Integer pageNo=getPageNo(start,length);
Integer pageNo=1;
Page page=new Page(pageNo,length);
${table.entityPath}Service.page(page,new QueryWrapper(param));
resJson.setDraw(draw++);
resJson.setRecordsTotal(page.getTotal());
resJson.setRecordsFiltered(page.getTotal());
resJson.setData(page.getRecords());
resJson.setSuccess(true);
}catch(Exception e){
resJson.setSuccess(false);
resJson.setError("異常資訊:{"+e.getClass().getName()+"}");
logger.info("異常資訊:{}"+e.getMessage());
}returnresJson;
}@RequestMapping(value= "/get${entity}ById", method =RequestMethod.GET)publicObject get${entity}ById(String id){
JSONResult resJson=new JSONResult<>();try{
${entity} param=${table.entityPath}Service.getById(id);
resJson.setData(param);
resJson.setSuccess(true);
}catch(Exception e){
resJson.setSuccess(false);
resJson.setMessage("異常資訊:{"+e.getClass().getName()+"}");
logger.info("異常資訊:{}"+e.getMessage());
}returnresJson;
}@RequestMapping(value= "/delete${entity}ById", method =RequestMethod.GET)publicObject delete${entity}ById(String id){
JSONResult resJson=new JSONResult<>();try{
resJson.setSuccess(${table.entityPath}Service.removeById(id));
}catch(Exception e){
resJson.setSuccess(false);
resJson.setMessage("異常資訊:{"+e.getClass().getName()+"}");
logger.info("異常資訊:{}"+e.getMessage());
}returnresJson;
}@RequestMapping(value= "/update${entity}ById", method =RequestMethod.POST)publicObject update${entity}ById(${entity} param){
JSONResult resJson=new JSONResult<>();try{
resJson.setSuccess(${table.entityPath}Service.updateById(param));
}catch(Exception e){
resJson.setSuccess(false);
resJson.setMessage("異常資訊:{"+e.getClass().getName()+"}");
logger.info("異常資訊:{}"+e.getMessage());
}returnresJson;
}@RequestMapping(value= "/add${entity}", method =RequestMethod.POST)publicObject add${entity}(${entity} param){
JSONResult resJson=new JSONResult<>();try{
resJson.setSuccess(${table.entityPath}Service.save(param));
}catch(Exception e){
resJson.setSuccess(false);
resJson.setMessage("異常資訊:{"+e.getClass().getName()+"}");
logger.info("異常資訊:{}"+e.getMessage());
}returnresJson;
}
}
6. html頁面模版 list.html.vm (這個目前生成的頁面和項目并不配套,先預留位置, 後續結合自己項目慢慢研究~)
首頁 進階檢索
角色名
查詢
重置
新增
批量删除
var $bootstrapTable= $('#empUserList'),
$query= $('#btn_query'),
$reset= $('#btn_reset'),
$remove= $('#btn_delete'),
$add= $('#btn_add'),
selections= [];//權限按鈕
$(function () {
$(".select2").select2();
$bootstrapTable#dian()bootstrapTable({
url: getRootPath()+'/a/${table.entityPath}/get${entity}PageList',
queryParams : queryParams,
classes:"table-striped table-hover table-bordered",
buttonsAlign:"right", //按鈕位置
toolbar: "#toolbar",//指定工具欄
uniqueId: "id", //每一行的唯一辨別
columns: [
{checkbox :true},
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
{title:'${field.comment}', field: '${field.propertyName}', align: 'center', valign: 'middle', sortable: true},
#end
#end {
title:'操作', field: 'id', align: 'center', valign: 'middle',
formatter: function (value, row, index) {return permissionButton.join('');
},
events: {'click [data-type="edit"]': function (e, value, row) {
layer_show("修改", getRootPath() + "/a/${table.entityPath}/${table.entityPath}Update?id=" + value, "800", "600");
},'click [data-type="delete"]': function (e, value, row) {
$.fn.modalConfirm('确定要删除所選資料?', function () {
$.ajax({
url: getRootPath()+ '/a/${table.entityPath}/${table.entityPath}Delete',
type:"Post",
data: {id: value},
dataType:"json",
success: function (result) {if (result > 0) {
$.fn.modalMsg("操作成功", "success");
}else{
$.fn.modalMsg("操作失敗", "error");
}
$remove#dian()prop('disabled', true);
$bootstrapTable#dian()bootstrapTable('refresh'); //從新加載資料
}
});
});
}
}
}
],
onLoadSuccess: function(){//加載成功時執行//layer.msg("加載成功");
},
onLoadError: function(){//加載失敗時執行
layer.msg("加載資料失敗", {time : 1500, icon : 2});
}
});//sometimes footer render error.
setTimeout(function () {
$bootstrapTable#dian()bootstrapTable('resetView', {
height:getHeight()
});
},300);
$(window).resize(function () {
$bootstrapTable#dian()bootstrapTable('resetView', {
height:getHeight()
});
});//點選行中的checkbox 和全選的checkbox事件
$bootstrapTable#dian()on('check.bs.table uncheck.bs.table ' +
'check-all.bs.table uncheck-all.bs.table', function () {
$remove#dian()prop('disabled', #tanh()$bootstrapTable#dian()bootstrapTable('getSelections').length);
selections=getIdSelections();
});
$query#dian()click(function () {
$bootstrapTable#dian()bootstrapTable('refresh'); //從新加載資料
});
$reset#dian()click(function () {
$(".form-inline .form-control").val("");
$bootstrapTable#dian()bootstrapTable('refresh'); //從新加載資料
});
$add#dian()click(function () {
layer_show("添加", getRootPath()+"/a/${table.entityPath}/${table.entityPath}Add","800","600");
});
$remove#dian()click(function () {if (selections.length < 1) {
$.fn.modalAlert('請選擇一條或多條資料進行删除!','error');
}else{//詢問框
$.fn.modalConfirm ('确定要删除所選資料?', function () {
$.ajax({
url: getRootPath()+'/a/${table.entityPath}/${table.entityPath}BatchDelete',
type:"Post",
data:{item:JSON.stringify(selections)},
dataType :"json",
success:function(result){if(result > 0){
$.fn.modalMsg("操作成功","success");
}else{
$.fn.modalMsg("操作失敗","error");
}
$remove#dian()prop('disabled', true);
$bootstrapTable#dian()bootstrapTable('refresh'); //從新加載資料
}
});
});
}
});$("input").keydown(function() {if (event.keyCode == "13") {//keyCode=13是Enter鍵
if ($query#dian()length > 0){
$bootstrapTable#dian()bootstrapTable('refresh'); //從新加載資料
}
}
});
});function getIdSelections() {return $.map($bootstrapTable#dian()bootstrapTable('getSelections'), function (row) {returnrow.id
});
}function queryParams(params) {
var temp= { //這裡的鍵的名字和控制器的變量名必須一直,這邊改動,控制器也需要改成一樣的
limit: params.limit, //頁面大小
offset: params.offset, //頁碼
sort: params.sort, //排序列名
order:params.order //排序方式//search:params.search,//搜尋框參數
};
getSearchFormData($("#searchForm"),temp);returntemp;
}