blog

実践:フロントエンドとバックエンドのコードを生成するためのキーは、Mybatis - Plusのコードジェネレータは、私が快適になる!

MyBatis-Plusのコードジェネレータは、コードジェネレータを介して迅速にエンティティ、マッパー、マッパーXML、サービス、...を生成することができます。...

Sep 24, 2020 · 20 min. read
シェア

序文

MyBatis-Plusのコードジェネレータは、AutoGeneratorを通して、エンティティ、マッパー、マッパーXML、Service、コントローラ、その他のモジュールとフロントエンドページコードを素早く生成し、開発効率を大幅に向上させます。

プロジェクト

このプロジェクトは、SpringBootのデモで、フロントエンドはfreemakerを使用し、データベースの永続化レイヤーはmybatisを使用します(mybatisの使用を考慮すると、まだ最も一般的であり、jpaとmybatisplusの使用はありません)。コードジェネレータで mysql に接続し、コモディティテーブルを例にして、各モジュールとフロントエンドページのコードを生成します。

このプロジェクトのすべてのコードとスクリプトは、この記事の最後にあります。

実用的な

データベーススクリプト

商品テーブル test_goods を作成します。

CREATE TABLE `test_goods` (
 `id` bigint(20) DEFAULT NULL COMMENT 'id',
 `goods_sn` varchar(45) DEFAULT NULL COMMENT '商品コード,
 `name` varchar(255) DEFAULT NULL COMMENT '商品名',
 `title` varchar(80) DEFAULT NULL COMMENT ' ,
 `price` decimal(10,2) DEFAULT NULL COMMENT ' ,
 `status` int(2) DEFAULT NULL COMMENT '商品のステータス,
 `sale_count` int(11) DEFAULT NULL COMMENT ' ,
 `create_date` datetime DEFAULT NULL COMMENT '作成された時間の,
 `modify_date` datetime DEFAULT NULL COMMENT '修正時間の
) ENGINE=InnoDB DEFAULT CHARSET=utf8

maven

 <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 取得/セットメソッドを簡素化する>
 <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>
		<!--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>

設定ファイル

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.:3306/myProject?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
 driver-class-name: com.mysql.jdbc.Driver
 redis:
 host: 192.
 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

テンプレートファイル

このプロジェクトでは、すべてのモジュールファイルはVelocityテンプレートエンジンを使って生成されています。ここで、Velocityの構文を簡単に紹介します。Velocityでは、例えば{table.entityName}はエンティティの名前、{authorfield in ${table.fields}) #end はテーブルのフィールドを走査します。以下に、いくつかのクラス、フロントエンドファイル、xmlファイルのテンプレートファイルを示します。

エンティティ・クラス・テンプレート

package ${package.Entity};
import java.math.BigDecimal;
import java.util.Date;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
 * データベーステーブル名 ${table.name}
 *
 * 
 * 
 */
@Getter
@Setter
@ToString
public class ${table.entityName} {
 #foreach($field in ${table.fields})
 /**
 * データベースのフィールド名 ${field.name}   ${field.type}
 */
 private ${field.propertyType} ${field.propertyName};
 #end
}

コントローラーテンプレート

package ${package.Controller};
import ${package.Entity}.${entity};
import ${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} フロントエンドコントローラ
 * </p>
 *
 * 
 * @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 = "詳細なエクスポート")
 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("クエリが間違っている",e);
 return JsonMapper.nonDefaultMapper().toJson(new Resp("false", e.getMessage()));
 }
 }
}

サービス・クラス・テンプレート

package ${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}  
 * </p>
 *
 * 
 * @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);
 return gm;
 }
}

Daoクラステンプレート

package ${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);
 /**
 * ページングクエリの条件に応じて
 * */
 long countForPage(Map<String,Object> searchMap);
 
}

Mapper.xmlテンプレート

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://.org/dtd/mybatis-3-.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
 #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
 <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
 <!-- -->
 delete from ${table.name}
 where
 #foreach($field in ${table.fields})
 #if(${field.keyFlag})##  
 ${field.name} = #{ ${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})##一般的なフィールドを生成する
 ${field.name}#if($foreach.hasNext),#end
 #end
 #end
 )
 values (
 #foreach($field in ${table.fields})
 #if(!${field.keyFlag})##一般的なフィールドを生成する
 #{ ${field.propertyName}}#if($foreach.hasNext),#end
 #end
 #end
 )
 </insert>
 <update id="updateByPrimaryKey" parameterType="${package.Entity}.${entity}">
 <!-- -->
 update ${table.name}
 set
 #foreach($field in ${table.fields})
 #if(!${field.keyFlag})##一般的なフィールドを生成する
 ${field.name} = #{ ${field.propertyName}} #if($foreach.hasNext),#end
 #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>

フロントエンドページ list.ftl テンプレート

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://..org/TR/xhtml1/DTD/xhtml1-.dtd">
 <#assign base=request.contextPath>
<html xmlns="http://..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(){
 //初期化コントロール
 $("#search-panel").omPanel({
 title : "条件検索",collapsible:false
 });
 // 
 $('#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:"エクスポートExcelの",
 id:"addbutton" ,
 icons : {left : '${base}/static/omui/images/export.png'},
 onClick:function()
 {
 exportUtil({
 title : "リストのエクスポート",
 exportUrl : "${base}/admin/${table.entityPath}/searchList",
 extraParam : $("#listForm").HForm('form2json')
 });
 }
 }
 ]
 });
 //初期化リスト
 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 : '作成された時間の, name : 'createDate', width : 150, align : 'left',sort:'serverSide',renderer :dataFormat1},
 {header : '修正時間の, 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){
 }
 });
 //初期化コントロール終了
 function getIds(datas) {
 var str = "";
 for (var i = 0; i < datas.length; i++) {
 str += datas[i].id + ",";
 }
 //最後のコンマを削除する
 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"> :</span>
 <select class="js-example-basic-single input-select" name="filter_EQS_status">
 <option value="0" selected> </option>
 <option value="1"> </option>
 <option value=""> </option>
 </select>
 <span class="label">携帯電話の番号</span>
 <input type="text" class="input-text" name="filter_LIKES_mobile" />
 <span class="label">連絡先</span>
 <input type="text" class="input-text" name="filter_LIKES_name" />
 <span class="label">作成時間:</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"> </span>
 </div>
 </form>
</div>
<div id="buttonbar"></div><!-- ツールバーの場所>
<table id="listGrid"></table> <!-- メインリストの場所--。>
</body>
</html>

コードジェネレータ

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;
/**
 * 補助的な生産のバックエンドの開発 開発のみ自分のローカルコードの変更では、提出しない
 * ddaoサービスコントローラのエンティティのJavaコードとフロントエンドのFLTファイルを する。
 * 唯一のリストのシナリオを実証する
 */
public class MpGenerator {
 //注:自分のローカルコードの変更でのみ開発、提出しない、提出しない提出しない
 //最初のステップは、Javaのソースコードのルートパスを格納するために自分のプロジェクトにjavaSrcDirを変更する
 static String javaSrcDir = "D:/Git_space/lunzijihua/codegenerator/src/main/java";
 static String resourceDir = "D:/Git_space/lunzijihua/codegenerator/src/main/resources";
 //2番目のステップは、フォルダのルートパスに格納されているftlファイルを開発したいモジュールの名前にpageRootDirを変更する
 static String pageRootDir ="D:/Git_space/lunzijihua/codegenerator/src/main/resources/templates/pages/";
 //あなたが小文字の生産エンティティサービスダオアクションフォルダとJavaコードは次のようになるパッケージ名を開発したいモジュールの名前にパッケージ名の変更を変更する3番目のステップ
 static String packageName = "user";//モジュールフォルダパッケージ名
 //4番目のステップは、小文字にftlファイルを格納するフォルダを開発したいモジュールの名前にpageDirNameを変更する
 static String pageDirName = "user";//モジュールページのフォルダ名
 //ステップ5テーブルの接頭辞が記入される。 ファイルが生成されるときに削除される。
 static String tablePrefix="test_";
 //ステップ6データベース内の対応するテーブルのフルネーム
 static String tableName="test_goods";
 /**
 * <p>
 * 自動コード生成
 * </p>
 */
 public static void main(String[] args) {
 AutoGenerator mpg = new AutoGenerator();
 // グローバル構成
 GlobalConfig gc = new GlobalConfig();
 gc.setOutputDir(javaSrcDir);
 gc.setFileOverride(true);
 gc.setActiveRecord(true);// ActiveRecordの機能を必要としないfalseに変更してください!
 gc.setEnableCache(false);// XML 第二レベルのキャッシュ
 gc.setBaseResultMap(true);// XML ResultMap
 gc.setBaseColumnList(true);// XML columList
 // .setKotlin(true) コトリンコードを生成するかどうか
 gc.setAuthor("liuzhinan");
 // カスタムファイルの命名に注意を払う %s 自動的にテーブルのエンティティ属性を入力する!
 gc.setMapperName("%sMybatisDao");
 // gc.setXmlName("%sDao");
 gc.setServiceName("%sService");
// gc.setServiceImplName("%sService");
 // 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("test");
 dsc.setPassword("123456");
 dsc.setUrl("jdbc:mysql://192.:3306/myProject?useSSL=false");
 mpg.setDataSource(dsc);
 // 戦略の構成
 StrategyConfig strategy = new StrategyConfig();
 // strategy.setCapitalMode(true);// グローバル大文字の命名ORACLE注
 strategy.setTablePrefix(new String[] { tablePrefix });// これは、テーブルの接頭辞に変更することができる
 strategy.setNaming(NamingStrategy.underline_to_camel);// テーブル名生成戦略
 strategy.setInclude(new String[] { tableName }); // テーブルを生成する必要がある
 // strategy.setExclude(new String[]{"test"}); // 生成されたテーブルを除く
 // カスタムエンティティの親クラス
 strategy.setSuperEntityClass("com.lzn.mybatisplus.codegenerator.entity.IdEntity");
 // カスタムエンティティ、パブリックフィールド
 // strategy.setSuperEntityColumns(new String[] { "id", "create_date","modify_date" });
 // カスタムマッパ親クラス
 // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
 // カスタムサービスの親クラス
 // strategy.setSuperServiceClass("com.baomidou.demo.TestService");
 // カスタムサービス実装クラスの親クラス
 // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl");
 // カスタムコントローラの親クラス
 // strategy.setSuperControllerClass("com.baomidou.demo.TestController");
 // エンティティは、フィールド定数を生成するかどうか
 // public static final String ID = "test_id";
 // strategy.setEntityColumnConstant(true);
 // エンティティは、ビルダーモデルであるかどうか
 // public User setName(String name) {this.name = name; return this;}
 // strategy.setEntityBuilderModel(true);
 mpg.setStrategy(strategy);
 //  
 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);
 // カスタム設定の注入は、VMの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");
 map.put("pageDirName",pageDirName);
 map.put("packageName",packageName);
 this.setMap(map);
 }
 };
 List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// cfg.setFileOutConfigList(focList);
// mpg.setCfg(cfg);
 //エクスポートビューのオブジェクトを生成する
 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";
 }
 });
 //エクセルエクスポートサービスクラスを生成する,
 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";
 }
 });
 //指定されたディレクトリにmybatisDaoファイルを生成する
 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";
 }
 });
 //指定されたディレクトリにマッパーファイルを生成する
 focList.add(new FileOutConfig("/templates/vm/mapper.xml.vm") {
 @Override
 public String outputFile(TableInfo tableInfo) {
 return resourceDir+"/mybatis/"+tableInfo.getEntityName()+"Mapper.xml";
 }
 });
 // カスタムxxリスト.ftl 生成
 focList.add(new FileOutConfig("/templates/vm/list.ftl.vm") {
 @Override
 public String outputFile(TableInfo tableInfo) {
 // カスタム入力ファイル名
 return pageRootDir+pageDirName+"/list.ftl";
 }
 });
 cfg.setFileOutConfigList(focList);
 mpg.setCfg(cfg);
 // 閉じるデフォルトのxmlの生成は、ルートディレクトリに世代を調整する
 TemplateConfig tc = new TemplateConfig();
 tc.setEntity("/templates/vm/entity.java.vm");
 tc.setService("/templates/vm/service.java.vm");
 tc.setServiceImpl(null);//生成しないようにNULLに設定する
 tc.setController("/templates/vm/controller.java.vm");
 tc.setMapper(null);
 tc.setXml(null);
 mpg.setTemplate(tc);
 // カスタムテンプレート構成は、ソースコードmybatis - plus / src / main / resources /テンプレート次の内容の変更をコピーすることができる,
 // 独自のプロジェクトのsrc/main/resources/templatesディレクトリに配置され、次のデフォルトの名前を設定することはできません、また、テンプレートの名前をカスタマイズすることができる
 // TemplateConfig tc = new TemplateConfig();
 // tc.setController("...");
 // tc.setEntity("...");
 // tc.setMapper("...");
 // tc.setXml("...");
 // tc.setService("...");
 // tc.setServiceImpl("...");
 // このような任意のモジュールとして、空またはNULLを設定した場合、モジュールが生成されない。
 // mpg.setTemplate(tc);
 // 世代の実装
 mpg.execute();
 // 印刷注入の設定はないことができる
 System.err.println(mpg.getCfg().getMap().get("abc"));
 }
}

コードジェネレーターのMainメソッドを実行

コードを実行すると、対応するディレクトリにファイルが自動的に生成されました。

プロジェクトの開始

そして、リストページのパス アクセスしてください。

エクスポートボタンをクリックします。

概要

この論文では、プロジェクトが自動的にフロントエンドとバックエンドのコードを生成するアイデアを提供する:あなたは、プロジェクトの追加、削除、およびビジネスへの変更のための標準化されたコードのセットを書くことができる、コードのテンプレートを記述し、コードジェネレータを介して、テーブルのデータベースを介して迅速にフロントとバックエンドのコードを生成することができますプロジェクトチームの開発効率を向上させる。

Read next

JavaScript基礎の復習

1.ループ ps: オブジェクト列挙可能プロパティ

Sep 24, 2020 · 2 min read