spring-boot mybatis-plus 集成 + 代码生成器自定义controller 模板

mybatis-plus3.x 代码生成器请看以下链接

https://blog.csdn.net/qq_33842795/article/details/103682488

 

maven依赖

spring boot 和 thymeleaf 结合 controller 返回的控制器路径不能以/ 开头 

否则运行没问题,发布之后就找不到文件

 

 
<mybatisplus-spring-boot-starter.version>1.0.4</mybatisplus-spring-boot-starter.version>
<mybatisplus.version>2.1.0</mybatisplus.version>
<!-- mybatis-plus begin -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatisplus-spring-boot-starter</artifactId>
   <version>${mybatisplus-spring-boot-starter.version}</version>
</dependency>
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus</artifactId>
   <version>${mybatisplus.version}</version>
</dependency>
 
<!-- 模板引擎 代码生成 -->
<dependency>
   <groupId>org.apache.velocity</groupId>
   <artifactId>velocity</artifactId>
   <version>1.7</version>
</dependency>

<!-- mybatis-plus end -->

myabtis配置类

 

#MyBatis
mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.dcy.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: com.baomidou.springboot.xxx
    #逻辑删除配置
    #logic-delete-value: 0
    #logic-not-delete-value: 1
    #自定义填充策略接口实现
    #meta-object-handler: com.baomidou.springboot.MyMetaObjectHandler
    #自定义SQL注入器
    #sql-injector: com.baomidou.springboot.xxx
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    #不加这个查询数据为空时,字段将被隐藏

call-setters-on-nulls: true

 

@EnableTransactionManagement
@Configuration
@MapperScan("com.dcy.mapper*")
public class MybatisPlusConfig {

    /**
     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
     */
    @Bean
    @Profile({"dev","test"})// 设置 dev test 环境开启
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        /*<!-- SQL 执行性能分析,开发环境使用,线上不推荐。 maxTime 指的是 sql 最大执行时长 -->*/
        //performanceInterceptor.setMaxTime(1000);
        /*<!--SQL是否格式化 默认false-->*/
        //performanceInterceptor.setFormat(true);
        return performanceInterceptor;
    }

    /**
     * mybatis-plus分页插件<br>
     * 文档:http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
        return paginationInterceptor;
    }
}

代码生成器  这里控制器用的自己写的模板

 

 
public class MpGenerator {

    /**
     * <p>
     * MySQL 生成演示
     * </p>
     */
    public static void main(String[] args) {
        AutoGenerator mpg = new AutoGenerator();
        // 选择 freemarker 引擎,默认 Veloctiy
        // mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir("E://test//");
        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("xxxx");

        // 自定义文件命名,注意 %s 会自动填充表实体属性!
        // gc.setMapperName("%sDao");
        // gc.setXmlName("%sDao");
        // gc.setServiceName("MP%sService");
        // gc.setServiceImplName("%sServiceDiy");
        // gc.setControllerName("%sAction");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setDbType(DbType.MYSQL);
        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定义数据库表字段类型转换【可选】
            @Override
            public DbColumnType processTypeConvert(String fieldType) {
                System.out.println("转换类型:" + fieldType);
                // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
                return super.processTypeConvert(fieldType);
            }
        });
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/nxxsba?characterEncoding=utf8");
        mpg.setDataSource(dsc);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // 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);
        mpg.setStrategy(strategy);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent("com.dcy");
        pc.setController("controller");
        pc.setEntity("model");
        mpg.setPackageInfo(pc);

        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】  ${cfg.abc}
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                this.setMap(map);
            }
        };

        // 自定义 xxListIndex.html 生成
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        focList.add(new FileOutConfig("/templatesMybatis/list.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E://test//html//" + tableInfo.getEntityName() + "ListIndex.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 自定义  xxAdd.html 生成
        focList.add(new FileOutConfig("/templatesMybatis/add.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E://test//html//" + tableInfo.getEntityName() + "Add.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        //  自定义 xxUpdate.html生成
        focList.add(new FileOutConfig("/templatesMybatis/update.html.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return "E://test//html//" + tableInfo.getEntityName() + "Update.html";
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 关闭默认 xml 生成,调整生成 至 根目录
        /*TemplateConfig tc = new TemplateConfig();
        tc.setXml(null);
        mpg.setTemplate(tc);*/

        // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
        // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
         TemplateConfig tc = new TemplateConfig();
         tc.setController("/templatesMybatis/controller.java.vm");
         tc.setService("/templatesMybatis/service.java.vm");
         tc.setServiceImpl("/templatesMybatis/serviceImpl.java.vm");
         tc.setEntity("/templatesMybatis/entity.java.vm");
         tc.setMapper("/templatesMybatis/mapper.java.vm");
         tc.setXml("/templatesMybatis/mapper.xml.vm");
        // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
         mpg.setTemplate(tc);

        // 执行生成
        mpg.execute();

        // 打印注入设置【可无】
        System.err.println(mpg.getCfg().getMap().get("abc"));
    }


}

模板文件  自定义controller模板文件   comtroller.java.vm

 

 
package ${package.Controller};


#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import com.alibaba.fastjson.JSON;
import com.dcy.constant.Constant;
import com.dcy.model.BootStrapTable;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author ${author}
 * @since ${date}
 */
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("/a#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} {
#end
    private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Autowired
    public ${table.serviceName} i${entity}Service;

    /**
     * 跳转列表页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(method= RequestMethod.GET,value = {"/${table.entityPath}Index"})
    public String index(HttpServletRequest request, Model model) {
        return "${table.entityPath}ListIndex";
    }

    /**
     * 分页查询数据
     *
     * @param bootStrapTable  分页信息
     * @param ${table.entityPath}   查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/get${entity}PageList")
    public Map<String, Object> get${entity}List(BootStrapTable<${entity}> bootStrapTable,${entity} ${table.entityPath}) {
        Map<String,Object> result = new HashMap<String,Object>();
        try {
            result = bootStrapTable.setRows(i${entity}Service.selectPage(bootStrapTable,${table.entityPath}));
        } catch (Exception e) {
            logger.error("get${entity}List -=- {}",e.toString());
            result.put(Constant.BOOTSTAP_TABLE_ROWS, new ArrayList<>());
            result.put(Constant.BOOTSTRAP_TABLE_TOTAL, 0);
        }
        return result;
    }

    /**
     * 跳转添加页面
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Add")
    public String ${table.entityPath}Add(HttpServletRequest request,HttpServletResponse response,Model model) {
        try {


        }catch (Exception ex){
            logger.error("${table.entityPath}Add -=- {}",ex.toString());
        }
        return "${table.entityPath}Add";
    }

    /**
     * 跳转修改页面
     * @param request
     * @param id  实体ID
     * @return
     */
    @RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Update")
    public String ${table.entityPath}Update(HttpServletRequest request,Long id) {
        try {
            ${entity} ${table.entityPath} = i${entity}Service.selectById(id);
            request.setAttribute("${table.entityPath}",${table.entityPath});
        }catch (Exception ex){
            logger.error("${table.entityPath}Update -=- {}",ex.toString());
        }
        return "${table.entityPath}Upd";
    }

    /**
     * 保存和修改公用的
     * @param ${table.entityPath}  传递的实体
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method=RequestMethod.POST,value="/${table.entityPath}Save")
    public int ${table.entityPath}Save(${entity} ${table.entityPath}) {
        int count = 0;
        try {
            count = i${entity}Service.insertOrUpdate(${table.entityPath}) ? 1 : 0;
        } catch (Exception e) {
            logger.error("${table.entityPath}Save -=- {}",e.toString());
        }
        return count;
    }

    /**
     * 根据id删除对象
     * @param id  实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method= RequestMethod.POST,value="/${table.entityPath}Delete")
    public int ${table.entityPath}Delete(Long id){
        int count = 0;
        try {
            count = i${entity}Service.deleteById(id) ? 1 : 0;
        }catch (Exception e){
            logger.error("${table.entityPath}Delete -=- {}",e.toString());
        }
        return count;
    }

    /**
     * 批量删除对象
     * @param item 实体集合ID
     * @return  0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method= RequestMethod.POST,value="/${table.entityPath}BatchDelete")
    public int deleteBatchIds(String item){
        int count = 0;
        try {
            List<Long> ids = (List<Long>) JSON.parse(item);
            count = i${entity}Service.deleteBatchIds(ids) ? 1 : 0;
        }catch (Exception e){
            logger.error("${table.entityPath}BatchDelete -=- {}",e.toString());
        }
        return count;
    }


}

entity.java.vm

 

 

package ${package.Entity};

#if(${activeRecord})
import java.io.Serializable;

#end
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${entityLombokModel})

import com.baomidou.mybatisplus.annotations.Version;

import lombok.Data;
import lombok.experimental.Accessors;
#end

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
@Accessors(chain = true)
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#else
public class ${entity} implements Serializable {
#end

    private static final long serialVersionUID = 1L;

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
   @TableId(value="${field.name}", type= IdType.AUTO)
#elseif(${field.convert})
    @TableId("${field.name}")
#end
## 普通字段
#elseif(${field.fill})
## -----   存在字段填充设置   -----
#if(${field.convert})
   @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
#else
   @TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
   @TableField("${field.name}")
#end
## 乐观锁注解
#if(${versionFieldName}==${field.name})
   @Version
#end
## 逻辑删除注解
#if(${logicDeleteFieldName}==${field.name})
    @TableLogic
#end
   private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

#if(!${entityLombokModel})
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("boolean")})
#set($getprefix="is")
#else
#set($getprefix="get")
#end

   public ${field.propertyType} ${getprefix}${field.capitalName}() {
      return ${field.propertyName};
   }

#if(${entityBuilderModel})
   public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#else
   public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
#end
      this.${field.propertyName} = ${field.propertyName};
#if(${entityBuilderModel})
      return this;
#end
   }
#end
#end

#if(${entityColumnConstant})
#foreach($field in ${table.fields})
   public static final String ${field.name.toUpperCase()} = "${field.name}";

#end
#end
#if(${activeRecord})
   @Override
   protected Serializable pkVal() {
#if(${keyPropertyName})
      return this.${keyPropertyName};
#else
      return this.id;
#end
   }

#end
#if(!${entityLombokModel})
   @Override
   public String toString() {
      return "${entity}{" +
#foreach($field in ${table.fields})
#if($!{velocityCount}==1)
         "${field.propertyName}=" + ${field.propertyName} +
#else
         ", ${field.propertyName}=" + ${field.propertyName} +
#end
#end
         "}";
   }
#end
}
 

 

 

 

mapper.java.vm

 

 

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};

/**
 * <p>
  * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}

 

mapper.xml.vm

 

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">

#if(${enableCache})
   <!-- 开启二级缓存 -->
   <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

#end
#if(${baseResultMap})
   <!-- 通用查询映射结果 -->
   <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
#foreach($field in ${table.fields})
#if(${field.keyFlag})##生成主键排在第一位
      <id column="${field.name}" property="${field.propertyName}" />
#end
#end
#foreach($field in ${table.commonFields})##生成公共字段
   <result column="${field.name}" property="${field.propertyName}" />
#end
#foreach($field in ${table.fields})
#if(!${field.keyFlag})##生成普通字段
      <result column="${field.name}" property="${field.propertyName}" />
#end
#end
   </resultMap>

#end
#if(${baseColumnList})
    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
#foreach($field in ${table.commonFields})
   #if(${field.name} == ${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end,
#end
        ${table.fieldNames}
    </sql>
#end
</mapper>
 

service.java.vm

 

 

 

package ${package.Service};

import com.baomidou.mybatisplus.plugins.Page;
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import com.dcy.model.BootStrapTable;

import java.util.List;

/**
 * <p>
 * $!{table.comment} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

    /**
     *  分页查询
     * @param bootStrapTable
     * @param ${table.entityPath}
     * @return
     */
    Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable,${entity} ${table.entityPath});




    List<AppCertificate> selectList(${entity} ${table.entityPath});
}
 

serviceImpl.java.vm

 

 

 

package ${package.ServiceImpl};

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.model.BootStrapTable;
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.dcy.utils.lang.StringUtils;

import java.util.List;
/**
 * <p>
 * $!{table.comment} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
@Transactional
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {


    @Autowired
    private ${table.mapperName} ${table.entityPath}Mapper;

    @Override
    public Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable, ${entity} ${table.entityPath}) {
        EntityWrapper<${entity}> entityWrapper = new EntityWrapper<${entity}>();
        getEntityWrapper(entityWrapper,${table.entityPath});
        return super.selectPage(bootStrapTable.getPagePlus(),entityWrapper);
    }

    @Override
    public List<${entity}> selectList(${entity} ${table.entityPath}) {
        EntityWrapper<${entity}> entityWrapper = new EntityWrapper<${entity}>();
        getEntityWrapper(entityWrapper,${table.entityPath});
        return super.selectList(entityWrapper);
    }

    /**
     *  公共查询条件
     * @param entityWrapper
     * @return
     */
    public EntityWrapper<${entity}> getEntityWrapper(EntityWrapper<${entity}> entityWrapper,${entity} ${table.entityPath}){
        //条件拼接
#foreach($field in ${table.fields})
    #if(!${field.keyFlag})
        if (StringUtils.isNotBlank(${table.entityPath}.${getprefix}${field.capitalName}())){
            entityWrapper.like(${entity}.${field.name.toUpperCase()},${table.entityPath}.${getprefix}${field.capitalName}());
        }
    #end
#end
        return entityWrapper;
    }
}
 

 

html 页面代码生成器   前端页面使用super ui  可自行修改 基本语法一样的

 

add.html.vm   默认都不能为空,生成之后 自行删减

 

 

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="common/common_header :: common_header(~{::title},~{},~{})">
    <title>添加首页</title>
</head>
<body style="height: 100%">
<section class="content">
    <div class="row">
        <form class="form-horizontal" id="form-admin-add" onsubmit="return false;">
            <div class="col-md-12">
    #foreach($field in ${table.fields})
        #if(!${field.keyFlag})##生成普通字段
            <div class="form-group">
                <label class="col-sm-2 control-label">${field.comment}</label>
                <div class="col-sm-10">
                    <input id="${field.propertyName}" name="${field.propertyName}" value="" class="form-control"/>
                </div>
            </div>
        #end
    #end

                <div class="form-group">
                    <label class="col-sm-2 control-label"></label>
                    <div class="col-sm-10">
                        <button class="btn btn-primary" id="submit" type="submit"><i class="fa fa-save"></i>&nbsp;保存
                        </button>
                        <button type="button" class="btn btn-danger" onclick="layer_close();"><i
                                class="fa fa-close"></i>&nbsp;关闭
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
</body>
<div th:replace="common/common_foot :: foot"></div>
<script th:src="@{/content/plugins/jquery.validation/jquery.validate.js}"></script>
<script th:src="@{/content/plugins/jquery.validation/validate-methods.js}"></script>
<script th:src="@{/content/common/validation/common.validation.js}"></script>
<script th:inline="javascript">#macro(dian).#end #set($bootstrapTable = '$table')

    $(function () {
        $(".select2").select2({
            placeholder: "请选择",
            width: "100%" //设置下拉框的宽度
        });
        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
            increaseArea: '20%' // optional
        });
        $("#form-admin-add").validate({
            rules: {
            #foreach($field in ${table.fields})
                #if(!${field.keyFlag})##生成普通字段
                    ${field.propertyName}: {
                        required: true
                    }#if(${table.fields.size()} != ${velocityCount}),
                    #end
                #end
            #end
            },
            onkeyup: false,
            submitHandler: function (form) {
                $.ajax({
                    url: getRootPath()+"/a/${table.entityPath}/${table.entityPath}Save",
                    type: "Post",
                    dataType: "json",
                    data: $(form).serialize(),
                    success: function (result) {
                        if (result > 0) {
                            opaler();
                        } else {
                            opalerNO();
                        }
                        //刷新父级页面
                        parent.$bootstrapTable#dian()bootstrapTable('refresh'); //再刷新DT
                    }
                });
            }
        });
    });
</script>
</html>

 

update.html.vm

 

 

 

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="common/common_header :: common_header(~{::title},~{},~{})">
    <title>修改首页</title>

</head>
<body style="height: 100%">
<section class="content">
    <div class="row">
        <form class="form-horizontal" id="form-admin-update" onsubmit="return false;">
            <div class="col-md-12">
                #foreach($field in ${table.fields})
                    #if(!${field.keyFlag})##生成普通字段
                        <div class="form-group">
                            <label class="col-sm-2 control-label">${field.comment}</label>
                            <div class="col-sm-10">
                                <input id="${field.propertyName}" name="${field.propertyName}" th:value="${${table.entityPath}.${field.propertyName}}" class="form-control"/>
                            </div>
                        </div>
                    #end
                #end
                <div class="form-group">
                    <label class="col-sm-2 control-label"></label>
                    <div class="col-sm-10">
                        <input id="id" name="id" type="hidden" th:value="${${table.entityPath}.id}" class="form-control"/>
                        <button class="btn btn-primary" id="submit" type="submit"><i class="fa fa-save"></i>&nbsp;保存
                        </button>
                        <button type="button" class="btn btn-danger" onclick="layer_close();"><i
                                class="fa fa-close"></i>&nbsp;关闭
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>
</section>
</body>
<div th:replace="common/common_foot :: foot"></div>
<script th:src="@{/content/plugins/jquery.validation/jquery.validate.js}"></script>
<script th:src="@{/content/plugins/jquery.validation/validate-methods.js}"></script>
<script th:src="@{/content/common/validation/common.validation.js}"></script>
<script th:inline="javascript">#macro(dian).#end #set($bootstrapTable = '$table')

    $(function () {

        $('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
            checkboxClass: 'icheckbox_square-blue',
            radioClass: 'iradio_square-blue',
            increaseArea: '20%' // optional
        });
        $(".select2").select2({
            placeholder: "请选择",
            width: "100%" //设置下拉框的宽度
        });
        $("#form-admin-update").validate({
            rules: {
        #foreach($field in ${table.fields})
            #if(!${field.keyFlag})##生成普通字段
                ${field.propertyName}: {
                required: true
            }#if(${table.fields.size()} != ${velocityCount}),
            #end
            #end
        #end
            },
            onkeyup: false,
            submitHandler: function (form) {

                $.ajax({
                    url: getRootPath()+"/a/${table.entityPath}/${table.entityPath}Save",
                    type: "Post",
                    dataType: "json",
                    data: $(form).serialize(),
                    success: function (result) {
                        if (result > 0) {
                            opaler();
                        } else {
                            opalerNO();
                        }
                        //刷新父级页面
                        parent.$bootstrapTable#dian()bootstrapTable('refresh'); //再刷新DT
                    }
                });
            }
        });
    });


</script>
</html>

 

list.html.vm    表格使用bootstrapTable 插件 权限使用shiro 标签  ,条件查询没有生成 具体业务,自行修改,

 

表格里面的按钮权限我暂时这么写的  ,如果有大神知道有更好的方式,麻烦给我留言  我修改过来  我也学习下

 

 

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:replace="common/common_header :: common_header(~{::title},~{},~{})">
    <title>首页</title>
</head>
<body>
<section class="content">

    <div class="row">
        <!-- BEGIN SAMPLE TABLE PORTLET-->
        <div class="col-md-12">
            <!-- BEGIN SAMPLE TABLE PORTLET-->
            <div class="box-body" style="padding-bottom:0px;">
                <div class="panel panel-default">
                    <div class="panel-heading">高级检索</div>
                    <div class="panel-body">
                        <form class="form-inline" method="post" id="searchForm" >
                            <div class="form-group">
                                <label for="name">角色名</label>
                                <input type="text" class="form-control" id="name" name="name" placeholder="用户名"/>
                                <input id="hiddenText" type="text" style="display:none" /><!-- 隐藏的  控制回车提交表单-->
                            </div>
                            <button shiro:hasPermission="sys:user:search" type="button" id="btn_query" class="btn btn-success"><i class="fa fa-search"></i>&nbsp;查询</button>
                            <button shiro:hasPermission="sys:user:search" type="button" id="btn_reset" class="btn btn-primary"><i class="fa fa-undo"></i>&nbsp;重置</button>
                        </form>
                    </div>
                </div>

                <div id="toolbar" class="btn-group">
                    <button shiro:hasPermission="sys:user:add" id="btn_add" type="button" class="btn btn-default">
                        <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
                    </button>
                    <button shiro:hasPermission="sys:user:delete" id="btn_delete" type="button" class="btn btn-default" disabled="disabled">
                        <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>批量删除
                    </button>
                </div>
                <div class="table-scrollable">
                    <table class="table-striped table-hover table-bordered"  id="empUserList">
                    </table>
                </div>
            </div>
            <!-- END SAMPLE TABLE PORTLET-->

        </div>
    </div>

</section>
</body>
<script th:inline="javascript">
    var permissionButton = [];//权限按钮
</script>
<script th:inline="javascript" shiro:hasPermission="sys:user:update">
    permissionButton.push('<a class="btn btn-icon-only" data-type="edit" href="javascript:void(0)" title="修改"><i class="glyphicon glyphicon-edit"></i></a>');
</script>
<script th:inline="javascript" shiro:hasPermission="sys:user:delete">
    permissionButton.push('<a class="btn btn-icon-only" data-type="delete" href="javascript:void(0)" title="删除"><i class="glyphicon glyphicon-remove"></i></a>');
</script>

<div th:replace="common/common_foot :: foot"></div>
<script th:src="@{/content/plugins/bootstrap-table/bootstrap-table.js}"></script>
<script th:src="@{/content/plugins/bootstrap-table/locale/bootstrap-table-zh-CN.js}"></script>
<script th:src="@{/content/common/common.server.js}"></script>
<script th:inline="javascript">#macro(dian).#end #set($bootstrapTable = '$table') #macro(tanh)!#end #set($query = '$query') #set($reset = '$reset') #set($remove = '$remove') #set($add = '$add')

    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 获取焦点 才能触发 刷新事件*/
        $("input").keydown(function() {
            if (event.keyCode == "13") {//keyCode=13是回车键
                if ($query#dian()length > 0){
                    $bootstrapTable#dian()bootstrapTable('refresh');   //从新加载数据
                }
            }
        });
    });


    /**
     * 返回所有的checked选中的值
     */
    function getIdSelections() {
        return $.map($bootstrapTable#dian()bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }

    /**
     * 查询条件与分页数据
     * @param params
     * @returns {{limit: (*|number), offset, sort, order}}
     */
    function queryParams(params) {
        var temp = {   //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
            limit: params.limit,   //页面大小
            offset: params.offset, //页码
            sort: params.sort,  //排序列名
            order:params.order //排序方式
            //search:params.search,   //搜索框参数
        };
        getSearchFormData($("#searchForm"),temp);
        return temp;
    }
</script>
</html>

 

 

 

 

评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值