preface

In daily software development, programmers often need to spend a lot of time writing CRUD, which is not only boring and inefficient, but also the code style of everyone is not uniform. MyBatis-Plus code generator, through the AutoGenerator can quickly generate Entity, Mapper, Mapper XML, Service, Controller and other modules and front-end page code, greatly improve the development efficiency.

Project introduction

In this project, springboot will be used for demonstration, Freemaker will be used for front-end, MyBatis will be used for database persistence layer (jPA and Mybatisplus will not be used since MyBatis is still the most commonly used), and file templates of each module will be configured through Velocity template engine. Connect to mysql through mybatis- Plus code generator, and use commodity table as an example to generate the code and front-end page of each module. (This project demonstrates only paging queries and exports).

All code and scripts in this project can be found at the end of the text address.

In actual combat

Database script

Create a test_Goods table

CREATE TABLE `test_goods` (
  `id` bigint(20) DEFAULT NULL COMMENT 'id',
  `goods_sn` varchar(45) DEFAULT NULL COMMENT 'Commodity Code',
  `name` varchar(255) DEFAULT NULL COMMENT 'Trade Name',
  `title` varchar(80) DEFAULT NULL COMMENT 'title',
  `price` decimal(10.2) DEFAULT NULL COMMENT 'price',
  `status` int(2) DEFAULT NULL COMMENT 'State of goods',
  `sale_count` int(11) DEFAULT NULL COMMENT 'sales',
  `create_date` datetime DEFAULT NULL COMMENT 'Creation time',
  `modify_date` datetime DEFAULT NULL COMMENT 'Modification time'
) ENGINE=InnoDB DEFAULT CHARSET=utf8
Copy the code

Maven rely on

  <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.1.4</version>
        </dependency>

        <! -- aspectj -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <scope>provided</scope>
        </dependency>
        <! --es-->

        <! Lombok simplifies get/set methods -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.10</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
		<! Select * from 'CSV';
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>3.8</version>
        </dependency>
		
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
    </dependencies>
Copy the code

The configuration file

mybatis:
  mapper-locations: classpath:mybatis/*Mapper.xml
  type-aliases-package: com.lzn.mybatisplus.codegenerator.entity

spring:
  datasource:
    username: root
    password: 123qwe
    url: JDBC: mysql: / / 192.168.0.1:3306 / myProject? useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
    driver-class-name: com.mysql.jdbc.Driver
  redis:
    host: 192.168. 01.
    password: 1234qwer
    port: 6379
  freemarker:
    template-loader-path: classpath:/templates/pages/
    cache: false
    charset: UTF-8
    check-template-location: true
    content-type: text/html
    expose-request-attributes: true
    expose-session-attributes: true
    suffix: .ftl
Copy the code

Template file

In this project, all module files are generated by Velocity template engine. Here is a brief introduction to the syntax of Velocity. Variables are represented in Velocity, such as {} to represent variables, such as: to represent variables, such as: {table.entityName} represents the entityName, field.name represents the field name, and the global variable {field.name} we defined in the AutoGenerator code generator represents the field name. The global variable field.name we defined in the AutoGenerator code generator represents the field name, and the global variables {author} and {date} we defined in the AutoGenerator code generator represent the author, date, etc. In Velocity, use # to indicate syntax, such as #foreach(field in ${table.fields}) #end to iterate over table fields. Here are some examples of template files for classes, front-end files, and XML files

Entity Class Template (Entity.java.vm)

packageThe ${package.Entity};

import java.math.BigDecimal;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

${table.name} **@author ${author}
 * @date ${date}
 */
@Getter
@Setter
@ToString
public class ${table.entityName}  {

    #foreach($field in ${table.fields})
    ${field.name} type ${field.type} */
    private ${field.propertyType}  ${field.propertyName};

    #end

}
Copy the code

Templates Controller (Controller. Java. Vm)

packageThe ${package.Controller};

importThe ${package.Entity}.${entity};
importThe ${package.Service}.${table.serviceName};
import com.lzn.mybatisplus.codegenerator.export.${table.entityName}VO;
import com.lzn.mybatisplus.codegenerator.export.${table.entityName}ExportService;
import com.lzn.mybatisplus.codegenerator.utils.entity.*;
import com.lzn.mybatisplus.codegenerator.utils.export.*;
import org.apache.commons.beanutils.ConvertUtils;
import com.lzn.mybatisplus.codegenerator.utils.ParameterUtil;
import com.lzn.mybatisplus.codegenerator.utils.entity.GridDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/** ** <p> * ${tablecomment} Front-end controller * </p> **@author ${author}
 * @since ${date}
 */
@Controller
@RequestMapping(value="/admin/${table.entityPath}")
public class ${table.controllerName}{
    private static Logger logger = LoggerFactory.getLogger(${table.controllerName}.class);

    @Resource
    private ${entity}Service ${table.entityPath}Service;



    @RequestMapping(value = "list", method = RequestMethod.GET)
    public String list(Model model){
        return "/admin/${cfg.pageDirName}/list";
    }

    @RequestMapping(value = "searchList", method = RequestMethod.POST)
    @ResponseBody
    @exportMethod (serviceClass = ${entity} exportService. class, memo = "Export details ")
    public String searchList(ServletRequest request,@ModelAttribute("page")  OmuiPage page){
        try {
            Map<String,Object> searchParam =    ParameterUtil.getParametersStartingWith(request, "filter_");
            GridDataModel<${entity}VO> gd =${table.entityPath}Service.findByPage(searchParam, page);
            return JsonMapper.nonDefaultMapper().toJson(gd);
        } catch (Exception e) {
            logger.error("Query error",e);
            return JsonMapper.nonDefaultMapper().toJson(new Resp("false", e.getMessage())); }}}Copy the code

Service class template (service.java.vm)

packageThe ${package.Service};



import org.springframework.stereotype.Service;
import com.lzn.mybatisplus.codegenerator.dao.${table.mapperName};
import com.lzn.mybatisplus.codegenerator.utils.entity.GridDataModel;
import com.lzn.mybatisplus.codegenerator.utils.entity.OmuiPage;
import com.lzn.mybatisplus.codegenerator.export.${table.entityName}VO;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/** * <p> * $! {tablecomment} Service class * </p> * *@author ${author}
 * @since ${date}
 */
@Service
public class ${table.serviceName} {

    @Resource
    private ${table.mapperName} ${table.entityPath}Dao;

    /** ** ** /
    public GridDataModel<${table.entityName}VO>  findByPage(Map<String, Object> searchParams, OmuiPage page){
        GridDataModel<${table.entityName}VO> gm = new GridDataModel<${table.entityName}VO>();
        searchParams.put("start", page.getStart());
        searchParams.put("limit", page.getLimit());
        long count = ${table.entityPath}Dao.countForPage(searchParams);
        List<${table.entityName}VO> list = ${table.entityPath}Dao.listForPage(searchParams);
        gm.setTotal(count);
        gm.setRows(list);
        returngm; }}Copy the code

Dao Class template (DAo.java.vm)

packageThe ${package.Mapper};

import com.lzn.mybatisplus.codegenerator.entity.${table.entityName};
import com.lzn.mybatisplus.codegenerator.export.${table.entityName}VO;
import java.util.List;
import java.util.Map;

public interface ${table.mapperName}  {
    ${table.name} */
    int deleteByPrimaryKey(Long id);

    ${table.name} */
    int insert(${table.entityName} record);

    ${table.name} */
    ${table.entityName} selectByPrimaryKey(Long id);

    ${table.name} */
    int updateByPrimaryKey(${table.entityName} record);

    /** ** ** /
    List<${table.entityName}VO> listForPage(Map<String,Object> searchMap);

    /** ** query (count) ** /
    long countForPage(Map<String,Object> searchMap);
    
}
Copy the code

Mapper. The XML template (vm) Mapper. XML.


      
<! DOCTYPEmapper PUBLIC "- / / mybatis.org//DTD Mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
    #if(${baseResultMap})
        <! -- Query mapping result -->
        <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.monfields})#<result column="${field.name}" property="${field.propertyName}" />#end #foreach($field in ${table.fields}) #if(! ${field.keyflag})## Generate a common field<result column="${field.name}" property="${field.propertyName}" />
                #end
            #end
        </resultMap>
    #end

    #if(${baseColumnList})
        <! -- Generic query result column -->
        <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

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
        <! -- -->Delete from ${table.name} where #foreach($field in ${table.fields}) #if(${field.keyflag})# ${field.propertyName} } #end #end</delete>

    <insert id="insert" parameterType="${package.Entity}.${entity}">
        <! -- -->
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
            SELECT LAST_INSERT_ID()
        </selectKey>insert into ${table.name} ( #foreach($field in ${table.fields}) #if(! ${field.keyflag})# if($foreach. HasNext),#end #end) values ($foreach ($field in) ${table.fields}) #if(! ${field.keyflag})# {${field.propertyName}}#if($foreach.hasNext),#end #end)</insert>

    <update id="updateByPrimaryKey" parameterType="${package.Entity}.${entity}">
        <! -- -->update ${table.name} set #foreach($field in ${table.fields}) #if(! ${field.keyflag})# if($foreach.hasNext),#end #end where ${field.keyflag} = #{${field.propertyName}} #if($foreach.hasNext),#end #end where #foreach($field in ${table.fields}) #if(${field.keyFlag}) id = #{ ${field.name} } #end #end</update>


    <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
        <! -- -->
        select
        <include refid="Base_Column_List" />
        from ${table.name}
        where id = #{ id }
    </select>

    <select id="countForPage" parameterType="map" resultType="Long">
        <! -- -->
        select
         count(*)
        from
        ${table.name}
        where 1=1
        <if test="beginDate ! = null and beginDate ! = "">and create_date <! [CDATA[>=]]> #{beginDate}</if>
        <if test="endDate ! = null and endDate ! = "">and create_date <! [CDATA[<=]]> #{endDate}</if>
    </select>

    <select id="listForPage" parameterType="map" 	resultType="com.lzn.mybatisplus.codegenerator.export.${table.entityName}VO">
        <! -- -->
        select
        <include refid="Base_Column_List" />
        from
        ${table.name}
        where 1=1
        <if test="beginDate ! = null and beginDate ! = "">and create_date <! [CDATA[>=]]> #{beginDate}</if>
        <if test="endDate ! = null and endDate ! = "">and create_date <! [CDATA[<=]]> #{endDate}</if>
        limit #{start}, #{limit}
    </select>
</mapper>
Copy the code

Front-end page list.ftl template (list.ftl.vm)

<! DOCTYPEhtml PUBLIC "- / / / / W3C DTD XHTML 1.0 Transitional / / EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <#assign base=request.contextPath>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>$! {tablecomment}</title>
<link href="${base}/static/omui/css/elegant/om-all.css" rel="stylesheet" type="text/css" />
<link href="${base}/static/admin/css/admin.css" rel="stylesheet" type="text/css" />

<script type="text/javascript" src="${base} / static/js/jquery - 1.7.1. Js." "></script>
<script type="text/javascript" src="${base}/static/js/HForm.js"></script>
<script type="text/javascript" src="${base}/static/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="${base}/static/omui/js/operamasks-ui.min.js"></script>
<script type="text/javascript" src="${base}/static/omui/js/common.js"></script>
<script type="text/javascript" src="${base}/static/bui/js/common.js"></script>
<script type="text/javascript" src="${base}/static/admin/js/export.js"></script>

<script type="text/javascript">


   $().ready(function(){

      // Initialize the controller
      $("#search-panel").omPanel({
         title : "Conditional search".collapsible:false
      });

      / / search
      $('#searchButton').bind('click'.function(e) {
           var data = $("#listForm").HForm('form2json');
           $('#listGrid').omGrid({extraData:data});
      });

      $("#start-time").omCalendar();
      $("#time-end").omCalendar();

       $('#searchButton').omButton({
         icons : {left : '${base}/static/omui/images/search.png'},width : 70
       });

        $(".input-select").change(function(){$('#searchButton').click();
        });

      $('#buttonbar').omButtonbar({
         btns : [{label:"Export Excel".id:"addbutton" ,
                  icons : {left : '${base}/static/omui/images/export.png'},
                  onClick:function()
                     {
                        exportUtil({
                           title : "List export".exportUrl : "${base}/admin/${table.entityPath}/searchList".extraParam : $("#listForm").HForm('form2json')}); }}});// Initialize the list
      var  height=$(document).height() -$('#search-panel').outerHeight()-$('#buttonbar').outerHeight()-40;
      $('#listGrid').omGrid({
         height:height,
         limit:20.method:'post'.singleSelect:false.extraData: $("#listForm").HForm('form2json'),
         dataSource : '${base}/admin/${table.entityPath}/searchList'.colModel: [{header : 'ID'.name : 'id'.width : 30.align : 'left'.sort:'serverSide'},
                  {header : 'Creation time'.name : 'createDate'.width : 150.align : 'left'.sort:'serverSide'.renderer :dataFormat1},
                  {header : 'Modification time'.name : 'modifyDate'.width : 150.align : 'left'.sort:'serverSide'.renderer :dataFormat1},
#foreach($field in ${table.fields})

#set($comment = "")
#set($type = "")
#set($isNullAble = true)
#set($defaultValue = false)
#set($listIsShow = true)
#set($listIsSearch = false)

#foreach( $e in $field.comment.split(","))
    #if( $foreach.count == 1 )
    #set($comment = $e)
    #elseif( $foreach.count == 2 )
    #set($type = $e)
    #elseif( $foreach.count == 3)
    #if($e == "YES")
    #set($isNullAble = true)
    #else
    #set($isNullAble = false)
    #end
    #elseif( $foreach.count == 4)
    #if($e == "true")
    #set($defaultValue = true)
    #else
    #set($defaultValue = false)
    #end
    #elseif( $foreach.count == 5)
    #if($e == "true")
    #set($listIsShow = true)
    #else
    #set($listIsShow = false)
    #end
    #elseif( $foreach.count == 6)
    #if($e == "true")
    #set($listIsSearch = true)
    #else
    #set($listIsSearch = false)
    #end
    #end
#end
         {header : '#if("$! comment" ! = "")${comment}#end'.name : '${field.propertyName}'.width : 90.align : 'left'.sort:'serverSide'#if($type == "timer"),renderer :dataFormat1 #end},
#end
         ],
         rowDetailsProvider:function(rowData){}});// Initialize the controller end
      function getIds(datas) {
         var str = "";
         for (var i = 0; i < datas.length; i++) {
            str += datas[i].id + ",";
         }
         // Remove the last comma (if you don't need to remove it, don't write it)
         if (str.length > 0) {
            str = str.substr(0, str.length - 1);
         }
         return str;
      }

      $('#searchButton').click();
   });



</script>
</head>
<body >

<div id="search-panel">
    <form id="listForm">
   <div>
      <span class="label">Status:</span>
      <select class="js-example-basic-single input-select"  name="filter_EQS_status">
         <option value="0" selected>To be processed</option>
         <option value="1">Have to deal with</option>
         <option value="">all</option>
      </select>
      <span class="label">Mobile phone no. :</span>
      <input type="text" class="input-text" name="filter_LIKES_mobile" />
      <span class="label">Contacts:</span>
      <input type="text" class="input-text" name="filter_LIKES_name" />
      <span class="label">Creation time:</span>
      <input id="start-time" style="width: 118px" name="filter_GTED_createDate"/>
      -
      <input id="time-end"  style="width: 118px" name="filter_LTED_createDate"/>
      <span id="searchButton">The query</span>
   </div>
   </form>
</div>

<div id="buttonbar"></div><! -- Toolbar location -->
<table id="listGrid"></table> <! -- Main list location -->

</body>
</html>
Copy the code

Code generator

package com.lzn.mybatisplus.codegenerator;

import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


** * Generate DDAO Service Controller Entity Java code and front-end FLT file. * Show only the list scenario */
public class MpGenerator {

    // Note: only make changes in your own code during development, do not commit, do not commit
    // The first step is to modify the javaSrcDir to the root path of the Java source code of your own project
    static String javaSrcDir = "D:/Git_space/lunzijihua/codegenerator/src/main/java";
    static String resourceDir = "D:/Git_space/lunzijihua/codegenerator/src/main/resources";
    // Step 2 change pageRootDir to the root path of the FTL folder in the name of the module you want to develop
    static String pageRootDir ="D:/Git_space/lunzijihua/codegenerator/src/main/resources/templates/pages/";


    // step 3 change packageName to the name of the module you want to develop the packageName to lowercase production entity service dao action folder and Java code will be below
    static String packageName = "user";// Module folder package name
    // Step 4 change pageDirName to the name of the module you want to develop
    static String pageDirName = "user";// Module page folder name
    // The prefix of step 5 will be removed when the build file is filled in
    static String tablePrefix="test_";
    // The full name of the corresponding table in the database
    static String tableName="test_goods";

    /** * 

* Code is automatically generated *

*/
public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // Global configuration GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(javaSrcDir); gc.setFileOverride(true); gc.setActiveRecord(true);Change the ActiveRecord feature to false if it is not required gc.setEnableCache(false);// XML level 2 cache gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList //.setkotlin (true) Whether to generate kotlin code gc.setAuthor("liuzhinan"); // Customize the file name, note that %s will automatically populate the table entity attributes! gc.setMapperName("%sMybatisDao"); // gc.setXmlName("%sDao"); gc.setServiceName("%sService"); // gc.setServiceImplName("%sService"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert(){ // Custom database table field type conversion @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("Conversion type:" + fieldType); // Attention!! ProcessTypeConvert has a default conversion. If it is not the result you want, please customize it or return it directly. return super.processTypeConvert(fieldType); }}); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("test"); dsc.setPassword("123456"); dsc.setUrl("JDBC: mysql: / / 192.168.0.1:3306 / myProject? useSSL=false"); mpg.setDataSource(dsc); // Policy configuration StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true); // Global uppercase name ORACLE note strategy.setTablePrefix(new String[] { tablePrefix });// This can be changed to your table prefix strategy.setNaming(NamingStrategy.underline_to_camel);// Table name generation policy strategy.setInclude(new String[] { tableName }); // The table to be generated // strategy.setExclude(new String[]{"test"}); // Exclude the generated table // Define the entity parent class strategy.setSuperEntityClass("com.lzn.mybatisplus.codegenerator.entity.IdEntity"); // Custom entities, public fields // strategy.setSuperEntityColumns(new String[] { "id", "create_date","modify_date" }); // Customize the mapper parent class // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); // Customize the service parent class // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); // Custom service implementation class parent class // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // Customize the controller parent class // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // whether to generate field constants (default false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // Whether [entity] is a builder model (default false) // public User setName(String name) {this.name = name; return this; } // strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); / / package configuration PackageConfig pc = new PackageConfig(); pc.setParent("com.lzn.mybatisplus.codegenerator"); pc.setModuleName(null); pc.setMapper("dao"); pc.setEntity("entity"); pc.setService("service"); pc.setServiceImpl("service.impl"); pc.setController("controller"); mpg.setPackageInfo(pc); CFG. ABC can be used in the VM. InjectionConfig cfg = new InjectionConfig() { @Override public void initMap(a) { Map<String, Object> map = new HashMap<String, Object>(); map.put("abc".this.getConfig().getGlobalConfig().getAuthor() + "-mp"); map.put("pageDirName",pageDirName); map.put("packageName",packageName); this.setMap(map); }}; List<FileOutConfig> focList =new ArrayList<FileOutConfig>(); // cfg.setFileOutConfigList(focList); // mpg.setCfg(cfg); // Generate an export view object focList.add(new FileOutConfig("/templates/vm/vo.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return javaSrcDir+"/com/lzn/mybatisplus/codegenerator/export/"+tableInfo.getEntityName()+"VO.java"; }});// Generate excel exported service class, focList.add(new FileOutConfig("/templates/vm/exportservice.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return javaSrcDir+"/com/lzn/mybatisplus/codegenerator/export/"+tableInfo.getEntityName()+"ExportService.java"; }});// Generate the mybatisDao file to the specified directory focList.add(new FileOutConfig("/templates/vm/mybatisdao.java.vm") { @Override public String outputFile(TableInfo tableInfo) { return javaSrcDir+"/com/lzn/mybatisplus/codegenerator/dao/"+tableInfo.getEntityName()+"MybatisDao.java"; }});// Generate mapper files to the specified directory focList.add(new FileOutConfig("/templates/vm/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return resourceDir+"/mybatis/"+tableInfo.getEntityName()+"Mapper.xml"; }});// Custom xxlist.ftl generation focList.add(new FileOutConfig("/templates/vm/list.ftl.vm") { @Override public String outputFile(TableInfo tableInfo) { // Customize the input file name return pageRootDir+pageDirName+"/list.ftl"; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);// Turn off default XML generation and adjust the generation to the root directory TemplateConfig tc = new TemplateConfig(); tc.setEntity("/templates/vm/entity.java.vm"); tc.setService("/templates/vm/service.java.vm"); tc.setServiceImpl(null);// Set this parameter to null tc.setController("/templates/vm/controller.java.vm"); tc.setMapper(null); tc.setXml(null); mpg.setTemplate(tc); / / custom template configuration, can copy the source code mybatis - plus/SRC/main/resources/templates below content changes, / / put your project of SRC/main/resources/templates directory, the default name can not configuration, can also custom template name // TemplateConfig tc = new TemplateConfig(); // tc.setController("..." ); // tc.setEntity("..." ); // tc.setMapper("..." ); // tc.setXml("..." ); // tc.setService("..." ); // tc.setServiceImpl("..." ); // None of the above modules will be generated if Null OR Null is set. // mpg.setTemplate(tc); // Perform the build mpg.execute(); // Print injection Settings System.err.println(mpg.getCfg().getMap().get("abc")); }}Copy the code

Execute the Main method of the code generator

After executing the code, a file is automatically generated in the corresponding directory

Start the project

Path and access list page http://localhost:8080/admin/goods/list

Click the export button (due to limited space, the exported view object, the exported Service class and the AOP aspect implementation are not described in this article, you can download the code to view them)

conclusion

This paper provides ideas for the automatic generation of front-end and back-end codes for the project: we can write a set of standard codes for the business of adding, deleting, modifying and checking the project to write code templates. Subsequently, the front-end and back-end codes can be generated quickly through the code generator and a table in the database to improve the development efficiency of the project team.

code

Github.com/pengziliu/G…