主要参考另外两篇博文,这里表示感谢
参考一(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是回车键
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;
}