Mybatisplus-Generator代码生成器-简单示例

简单示例

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;

/**
 * @author my
 * @Description 代码生成器
 * @since 2021-17-18
 */
public class CodeGenerator {

    private static final String URL = "jdbc:mysql://127.0.0.1:3306/mxy?serverTimezone=GMT%2B8&useSSL=false";
    private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String AUTHOR = "my";

    public static void main(String[] args) {
        String schemaName = "mxy";
        // 表名,多个英文逗号分割
        //String[] tableName = new String[] { "sys_role_menu","sys_oper_log","sys_menu","sys_dict_type","sys_dict_data" };
        String[] tableName = new String[]{"sys_oper_log"};
        
        String author = "mengyao";

        String parent = "com.mxy";
        String moduleName = "system";
        String entityPath = "entity";
        String controllerPath = "controller";
        String servicePath = "service";
        String serviceImplPath = "service.impl";
        String mapperXmlPath = "mapper.xml";
        String mapperPath = "mapper";

        String path = "D:\\work\\mxy\\mxy_daily_blog\\mxy_business\\mxy_system";
        String genPath = "D:\\work\\mxy\\mxy_daily_blog\\mxy_common\\mxy_common_core";
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        // 生成文件的输出目录
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(path + "/src/main/java");
        // 是否打开输出目录,默认true
        gc.setOpen(false);
        // 是否覆盖已有文件,默认false
        gc.setFileOverride(true);
        // 是否在xml中添加二级缓存配置,默认false
        gc.setEnableCache(false);
        // 开发者
        gc.setAuthor(AUTHOR);
        // 开启 swagger2 模式,默认false
        gc.setSwagger2(true);
        // 开启 BaseResultMap,默认false
        gc.setBaseResultMap(true);
        // 开启 通用查询结果列
        gc.setBaseColumnList(true);
        // 指定生成的主键的ID类型,默认null
        gc.setIdType(IdType.AUTO);
        //设置datetime类型为Date
        gc.setDateType(DateType.ONLY_DATE);
        //开启 ActiveRecord 模式
        gc.setActiveRecord(true);
        gc.setEntityName("%s");
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setSchemaName(schemaName);
        dsc.setUrl(URL);
        dsc.setDriverName(DRIVER_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(parent)
                .setModuleName(moduleName)
                .setMapper(mapperPath)
                .setService(servicePath)
                .setServiceImpl(serviceImplPath)
                .setController(controllerPath)
                .setEntity(entityPath)
                .setXml(mapperXmlPath);
        mpg.setPackageInfo(pc);


        // 自定义需要填充的字段 数据库中的字段(可忽略)
        List<TableFill> tableFillList = new ArrayList<>();
        tableFillList.add(new TableFill("create_time", FieldFill.INSERT));
        tableFillList.add(new TableFill("update_time", FieldFill.UPDATE));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        // 表名生成策略(下划线转驼峰命名)
        strategy.setNaming(NamingStrategy.underline_to_camel);
        // 列名生成策略(下划线转驼峰命名)
        //strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        // 是否生成实体时,生成字段注解
        strategy.setEntityTableFieldAnnotationEnable(false);
        // 是否启动Lombok配置
        strategy.setEntityLombokModel(true);
        // 是否启动REST风格配置
        strategy.setRestControllerStyle(true);
        //自动填充设置
        strategy.setTableFillList(tableFillList);
        //逻辑删除属性名称
        strategy.setLogicDeleteFieldName("is_delete");

        strategy.setSuperEntityClass("com.mxy.common.core.entity.vo.BaseEntity");

        // 自定义实体父类
//        strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
        // 自定义controller父类
//        strategy.setSuperControllerClass("pro.nbbt.base.controller.BaseController");
        // 自定义service父接口
//        strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService");
        // 自定义service实现类
//        strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl");
        // 自定义mapper接口
//        strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper");
        // 自定义基础的Entity类,公共字段
//        strategy.setSuperEntityColumns("user_id");
        // 表名
        strategy.setInclude(tableName);
        mpg.setStrategy(strategy);


        // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();


        // 调整 xml 生成目录演示
        focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return path + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        //调整 entityVO 生成目录
        focList.add(new FileOutConfig("/templates/entityVo.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return path + "/src/main/java/com/mxy/system/entity/vo/" + tableInfo.getEntityName() + "VO.java";
            }
        });

        //调整 entity 生成目录
        focList.add(new FileOutConfig("/templates/entity.java.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return genPath + "/src/main/java/com/mxy/common/core/entity/" + tableInfo.getEntityName() + ".java";
            }
        });

        //调整 vue 生成目录
        focList.add(new FileOutConfig("/templates/index.vue.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return genPath + "/src/main/java/com/mxy/common/core/entity/" + tableInfo.getEntityName() + ".vue";
            }
        });

        //调整 vue 生成目录
        focList.add(new FileOutConfig("/templates/js.js.vm") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return genPath + "/src/main/java/com/mxy/common/core/entity/" + tableInfo.getEntityName() + ".js";
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

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

        // 执行
        mpg.execute();
    }

}

模板

controller.java.vm
 package ${package.Controller};

import com.mxy.common.log.annotation.SysLog;
import com.mxy.common.log.enums.OperType;
import ${package.Entity}.vo.${entity}VO;
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end

/**
 * <p>
 * $!{table.comment} 前端控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Api(value = "${table.comment}",tags = "${table.comment}")
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("/api/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end

#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end

    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    /**
     * @Description 查询${table.comment}列表
     * @author ${author}
     * @date ${date}
     */
    @SysLog(module = "查询${table.comment}列表")
    @ApiOperation(value = "查询${table.comment}列表")
    @PostMapping("/getList")
    public String getList(@RequestBody ${entity}VO ${table.entityPath}VO) {
        return ${table.entityPath}Service.getList(${table.entityPath}VO);
    }

    /**
     * @Description 新增${table.comment}
     * @author ${author}
     * @date ${date}
     */
    @SysLog(module = "新增${table.comment}", operType = OperType.ADD)
    @ApiOperation(value = "新增${table.comment}")
    @PostMapping("/add")
    public String add(@RequestBody ${entity}VO ${table.entityPath}VO) {
        return ${table.entityPath}Service.add(${table.entityPath}VO);
        }

    /**
     * @Description 编辑${table.comment}
     * @author ${author}
     * @date ${date}
     */
    @SysLog(module = "编辑${table.comment}", operType = OperType.UPDATE)
    @ApiOperation(value = "编辑${table.comment}")
    @PostMapping("/edit")
    public String edit(@RequestBody ${entity}VO ${table.entityPath}VO) {
        return ${table.entityPath}Service.edit(${table.entityPath}VO);
        }

    /**
     * @Description 删除${table.comment}
     * @author ${author}
     * @date ${date}
     */
    @SysLog(module = "删除${table.comment}", operType = OperType.DELETE)
    @ApiOperation(value = "删除${table.comment}")
    @PostMapping("/delete")
    public String delete(@RequestBody ${entity}VO ${table.entityPath}VO) {
        return ${table.entityPath}Service.delete(${table.entityPath}VO);
        }

}

#end
service.java.vm
 package ${package.Service};

import com.mxy.common.core.entity.${entity};
import ${superServiceClassPackage};
import ${package.Entity}.vo.${entity}VO;

/**
 * <p>
 * $!{table.comment} 服务类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

    /**
     * 查询${table.comment}列表
     */
    public String getList(${entity}VO ${table.entityPath}VO);

    /**
    * 新增${table.comment}
    */
    public String add(${entity}VO ${table.entityPath}VO);

    /**
    * 编辑${table.comment}
    */
    public String edit(${entity}VO ${table.entityPath}VO);

    /**
    * 删除${table.comment}
    */
    public String delete(${entity}VO ${table.entityPath}VO);

}
#end
serviceImpl.java.vm
 package ${package.ServiceImpl};

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mxy.common.core.constant.BaseMessage;
import com.mxy.common.core.entity.SelfUserEntity;
import com.mxy.common.core.utils.ServiceResult;
import com.mxy.security.common.util.SecurityUtil;
import com.mxy.common.core.entity.${entity};
import ${package.Entity}.vo.${entity}VO;
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;

/**
 * <p>
 * $!{table.comment} 服务实现类
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {

}
#else
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

    @Override
    public String getList(${entity}VO ${table.entityPath}VO) {
        QueryWrapper queryWrapper = new QueryWrapper();
        Page<${entity}> page = new Page<>();
        page.setCurrent(${table.entityPath}VO.getCurrentPage());
        page.setSize(${table.entityPath}VO.getPageSize());
        IPage<${entity}> pageList = this.page(page, queryWrapper);
        return ServiceResult.success(pageList);
    }

    @Override
    public String add(${entity}VO ${table.entityPath}VO) {
        SelfUserEntity userDetails = SecurityUtil.getUserInfo();
        ${entity} ${table.entityPath} = new ${entity}();
        BeanUtils.copyProperties(${table.entityPath}VO, ${table.entityPath});
        ${table.entityPath}.setCreateUser(userDetails.getUsername());
        Boolean result = ${table.entityPath}.insert();
        if (result) {
            return ServiceResult.successMsg(BaseMessage.INSERT_SUCCESS);
        } else {
            return ServiceResult.successMsg(BaseMessage.INSERT_FAIL);
        }
    }

    @Override
    public String edit(${entity}VO ${table.entityPath}VO) {
        SelfUserEntity userDetails = SecurityUtil.getUserInfo();
        ${entity} ${table.entityPath} = new ${entity}();
        BeanUtils.copyProperties(${table.entityPath}VO, ${table.entityPath});
        ${table.entityPath}.setUpdateUser(userDetails.getUsername());
        Boolean result = ${table.entityPath}.updateById();
        if (result) {
            return ServiceResult.successMsg(BaseMessage.UPDATE_SUCCESS);
        } else {
            return ServiceResult.successMsg(BaseMessage.UPDATE_FAIL);
        }
    }

    @Override
    public String delete(${entity}VO ${table.entityPath}VO) {
        ${entity} ${table.entityPath} = new ${entity}();
        BeanUtils.copyProperties(${table.entityPath}VO, ${table.entityPath});
        Boolean result = ${table.entityPath}.deleteById();
        if (result) {
            return ServiceResult.successMsg(BaseMessage.DELETE_SUCCESS);
        } else {
            return ServiceResult.successMsg(BaseMessage.DELETE_FAIL);
        }
    }

}
#end
entity.java.vm
 package com.mxy.common.core.entity;

#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end

/**
 * <p>
 * $!{table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
  #if(${superEntityClass})
@EqualsAndHashCode(callSuper = true)
  #else
@EqualsAndHashCode(callSuper = false)
  #end
  #if(${chainModel})
@Accessors(chain = true)
  #end
#end
#if(${table.convert})
@TableName("${table.name}")
#end
#if(${swagger2})
@ApiModel(value="${entity}对象", description="$!{table.comment}")
#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

#if(${entitySerialVersionUID})
    private static final long serialVersionUID=1L;
#end
## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})

#if(${field.keyFlag})
#set($keyPropertyName=${field.propertyName})
#end
#if("$!field.comment" != "")
  #if(${swagger2})
    /**
     * ${field.comment}
     */
  #else
    /**
     * ${field.comment}
     */
  #end
#end
#if(${field.keyFlag})
## 主键
  #if(${field.keyIdentityFlag})
    @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
  #elseif(!$null.isNull(${idType}) && "$!idType" != "")
  @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
  #elseif(${field.convert})
    @TableId("${field.annotationColumnName}")
  #end
## 普通字段
#elseif(${field.fill})
## -----   存在字段填充设置   -----
  #if(${field.convert})
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
  #else
  @TableField(fill = FieldFill.${field.fill})
  #end
#elseif(${field.convert})
    @TableField("${field.annotationColumnName}")
#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(${chainModel})
    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(${chainModel})
        return this;
  #end
    }
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--

#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 null;
  #end
    }

#end
#if(!${entityLombokModel})
    @Override
    public String toString() {
        return "${entity}{" +
  #foreach($field in ${table.fields})
    #if($!{foreach.index}==0)
        "${field.propertyName}=" + ${field.propertyName} +
    #else
        ", ${field.propertyName}=" + ${field.propertyName} +
    #end
  #end
        "}";
    }
#end
}
entityVo.java.vm
 package ${package.Entity}.vo;

#if(${entityLombokModel})
import lombok.Data;
import lombok.EqualsAndHashCode;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
import com.mxy.common.core.entity.vo.BaseVO;
import com.mxy.common.core.entity.${entity};

import java.util.Date;
/**
 * <p>
 * $!{table.comment}-VO
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${entityLombokModel})
@Data
#end
#if(${superEntityClass})
public class ${entity}VO extends BaseVO<${entity}> {
#end

## ----------  BEGIN 字段循环遍历  ----------
#foreach($field in ${table.fields})
  #if("$!field.comment" != "")
    /**
     * ${field.comment}
     */
  #end
    private ${field.propertyType} ${field.propertyName};
#end
## ----------  END 字段循环遍历  ----------

}
mapper.java.vm
 package ${package.Mapper};

import com.mxy.common.core.entity.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper;

/**
 * <p>
 * $!{table.comment} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
#if(${kotlin})
@Mapper
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
@Mapper
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
#end
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="com.mxy.common.core.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">
        WHERE 1 = 1
#foreach($field in ${table.fields})
    <if test="${field.propertyName}!=null and ${field.propertyName}!=''">
        AND ${field.name} = #{${field.propertyName}}
    </if>
#end
    </sql>

#end
</mapper>
index.vue.vm
 <template>
  <div class="app-container">
    <!--查询-->
    <div class="filter-container">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input placeholder="请输入名称" v-model="listQuery.nickName" clearable @keyup.enter.native="handleFilter">
            <template slot="prepend">姓名</template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button class="filter-item" style="margin-left: 10px;" @click="handleFilter" size="small">
            查询
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" @click="handleRest" size="small">
            重置
          </el-button>
          <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" size="small">
            新增
          </el-button>
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <el-table
      :data="list"
      style="width: 100%" :row-style="{height:'40px'}"
      :cell-style="{padding:'0px'}" v-loading="listLoading"
      element-loading-spinner="el-icon-loading">
      <el-table-column type="index" width="50" align="center"/>
#foreach($field in ${table.fields})
  #if(!${field.keyFlag})##生成普通字段
  <el-table-column prop="${field.propertyName}" label="${field.comment}" show-overflow-tooltip align="center"></el-table-column>
  #end
#end
      <el-table-column label="操作" align="center" width="230" class-name="small-padding">
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleUpdate(row)" type="text">编辑</el-button>
          <el-button size="mini" @click="handleView(row)" type="text">详情</el-button>
          <el-popconfirm confirm-button-text='删除' cancel-button-text='取消' icon="el-icon-info"
                         icon-color="red" title="确定删除吗?" @confirm="handleDelete(row)">
            <el-button slot="reference" size="mini" type="text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
                @pagination="getList"/>

    <!--新增/修改页-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px"
               style="width: 100%; margin-left:0px;">
#foreach($field in ${table.fields})
  #if(!${field.keyFlag})##生成普通字段
  <el-form-item label="${field.comment}">
  <el-input v-model="temp.${field.propertyName}"/>
  </el-form-item>
  #end
#end
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogStatus==='add'?createData():updateData()">
          提交
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <!-- 详情 -->
    <el-dialog title="详情" :visible.sync="dialogFormVisibleView" width="700px" append-to-body>
      <el-form ref="dataForm" :model="temp" label-width="120px" size="mini">
        <el-row>

#foreach($field in ${table.fields})
  #if(!${field.keyFlag})##生成普通字段
  <el-col :span="12">
  <el-form-item label="${field.comment}:">{{ temp.${field.propertyName} }}</el-form-item>
  </el-col>
  #end
#end
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleView = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getList,add,edit,deleteData} from '@/api/sys/user/user'
import {addMsg,editMsg,delMsg} from "@/api/common/common";
import Pagination from '@/components/Pagination' // 分页

export default {
  name: '${entity}Table',
  components: {Pagination},
  filters: {},
  data() {
    return {
      list: null, //表格列表数据
      total: 0, // 总条数
      listLoading: true, // 列表加载圈
      listQuery: {
        currentPage: 1,
        pageSize: 10
      },
      temp: {
#foreach($field in ${table.fields})
    ${field.propertyName}:'',
#end
      },
      dialogFormVisible: false, //控制新增页关闭
      dialogFormVisibleView: false, //控制新增页关闭
      dialogStatus: '', // 判断当前操作是新增还是修改
      textMap: {
        add: '新增',
        edit: '编辑'
      },
      rules: {}
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /*列表查询*/
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    /*条件查询*/
    handleFilter() {
      this.listQuery.currentPage = 1
      this.getList()
    },
    /*条件重置*/
    handleRest() {},
    /*表单重置*/
    resetTemp() {
      this.temp = {
  #foreach($field in ${table.fields})
      ${field.propertyName}:'',
  #end
      }
    },
    /*新增跳转*/
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
    },
    /*新增提交*/
    createData() {
      add(this.temp).then(() => {
        addMsg();
        this.dialogFormVisible = false
        this.getList();
      })
    },
    /*修改跳转*/
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'edit'
      this.dialogFormVisible = true
    },
    /*修改提交*/
    updateData() {
      edit(this.temp).then(() => {
        editMsg();
        this.dialogFormVisible = false
        this.getList();
      })
    },
    /*数据删除*/
    handleDelete(row) {
#foreach($field in ${table.fields})
  #if(${field.keyFlag})##生成主键排在第一位
     this.temp.${field.propertyName} = row.${field.propertyName};
  #end
#end
      deleteData(this.temp).then(() => {
        delMsg();
        this.dialogFormVisible = false
        this.getList();
      })
    },
    /*数据详情*/
    handleView(row) {
      this.dialogFormVisibleView = true;
      this.temp = row;
    }
  }
}
</script>
<style>
/*新增页按钮居中--(写法暂定)*/
.dialog-footer {
  text-align: center;
}

.el-dialog__body {
  padding: 10px 10px;
}

.filter-container {
  margin-bottom: 18px;
}
</style>
js.js.vm
 import request from '@/utils/request'

/*列表查询*/
export function getList(data) {
    return request({
        url: '/${table.entityPath}/getList',
        method: 'post',
        data
    })
}
/*新增*/
export function add(data) {
    return request({
        url: '/${table.entityPath}/add',
        method: 'post',
        data
    })
}
/*修改*/
export function edit(data) {
    return request({
        url: '/${table.entityPath}/edit',
        method: 'post',
        data
    })
}
/*删除*/
export function deleteData(data) {
    return request({
        url: '/${table.entityPath}/delete',
        method: 'post',
        data
    })
}
posted @ 2022-12-12 10:54  许孟  阅读(186)  评论(0编辑  收藏  举报