How to make mybatis generate code automatically to improve development efficiency

osc_vpxa23em 2020-11-10 13:38:52
make mybatis generate code automatically

 Source :
In the use of mybatis In the process , When handwriting JavaBean and XML When I write more and more , More and more agree to make mistakes . This repetitive work , We certainly don't want to do so much .

not so bad , mybatis Provides us with powerful code generation --MybatisGenerator.

Through simple configuration , We can generate various types of entity classes , Mapper Interface , MapperXML file , Example Object etc. . Through these generated files , We can easily add, delete, modify and query a single table .

The following tools use IDEA

1 Create a code generator

1.1 establish Maven project

1.1.1 Select new project from the menu

File | New | Project

1.1.2 Choose the one on the left Maven

Because we're just creating a normal project , Click here Next that will do .

1.1.3 Input GroupId and ArtifactId

  • In my project ,

GroupId fill com.homejim.mybatis

ArtifactId fill mybatis-generator

Click on Next.

1.1.4 Finish

Go through the above steps , An ordinary Maven The project is created .

1.2 To configure generator.xml

The name doesn't matter , Just follow the one below pom.xml The correspondence in the document is good .

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC
        "-// MyBatis Generator Configuration 1.0//EN"
        "" >
    <!--  Local database driver jar Full path of package  -->
    <classPathEntry location="C:\Users\\Administrator\\.m2\repository\\mysql\\mysql-connector-java\\8.0.12\\mysql-connector-java-8.0.12.jar"/>
    <context id="context" targetRuntime="MyBatis3">
            <property name="suppressAllComments" value="false"/>
            <property name="suppressDate" value="true"/>
        <!--  Database configuration  -->
            <property name="forceBigDecimals" value="false"/>
        <!--  Where entity classes are generated  -->
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        <!-- *Mapper.xml  The location of the file   sqlMapGenerator-->
            <property name="enableSubPackages" value="false"/>
        <!-- Mapper  Location of interface files  -->
        <javaClientGenerator type="XMLMAPPER"
            <property name="enableSubPackages" value="false"/>
        <!--  Configuration of related tables  -->
        <table tableName="blog" />

Something needs to be changed :

  1. Local database driver jar Full path of package ( It has to be changed ).

  2. Database configuration ( It has to be changed

  3. Configuration of related tables ( It has to be changed

  4. Location of entity class generation and storage .

  5. MapperXML The location where the generated files are stored .

  6. Mapper Where the interface is stored .

If you don't know how to change , Please look at the back Configuration details .

1.3 To configure pom.xml

Add something to the original .

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""
    <!-- Add... To the original   That's it -->
                   <!-- Notice here ,  The file matches the file above -->
                        <id>Generate MyBatis Artifacts</id>
    <!-- To this end -->

It should be noted that configurationFile The document in refers to generator.xml. So the path is the relative path of the file , The name is the same as the file .

Here we are , mybatis-generator You can use it .

1.4 Use and test

1.4.1 open Maven Projects View

stay IDEA On , open :

View | Tools | Windwos | Maven Projects

Maven Project window

1.4.2 Maven Projects Middle double click mybatis-generator

On the right, you can see Maven Projects 了 . find mybatis-generator plug-in unit .

mybatis-generator | Plugins | mybatis-generator | mybatis-generator

Running plug-ins

1.4.3 Double-click on the run

After correct operation , The generated code , The following structure is obtained

2 XML Configuration details

It's not cool just to use it as simple as above . Then we can change generator.xml Configuration file to generate the configuration .

2.1 first

Official documents for reference .

Good English : Official website .

Chinese translation : Translated website

2.2 It's not on the official website

2.2.1 property label

The tag is only used to specify the attributes of elements in the official website , As for how to use it, there is no detailed explanation . Separator related

<property name="autoDelimitKeywords" value="true"/>
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>

The above configuration corresponds to mysql, When the fields in the database are the same as the keywords in the database , You'll use the separator .

For example, our data column is delete, According to the above configuration , Where it appears , It becomes delete. code

The default is to use the encoding of the current system environment , Can be configured as GBK or UTF-8.

<property name="javaFileEncoding" value="UTF-8"/>

I think the project is UTF-8, If you specify a build GBK, Then automatically generated Chinese is garbled code . format

<!-- Format generated  Java  Code -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- Format generated  XML-->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>

These are obviously customizable .

2.2.2 plugins label

plugins Tags are used to extend or modify code generated by code generators .

In the generated XML in , It's not **** This label's . This tag is configured for caching .

If we want to generate this tag , Then you can. plugins To configure .

<plugin type="org.mybatis.generator.plugins.CachePlugin" >
            <property name="cache_eviction" value="LRU"/>

Like what you want to generate JavaBean It can be realized by itself Serializable Interface .

<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
Serialization interface implementation

You can also customize plug-ins .

These plug-ins are very useful , I feel that I can open an article to explain .

2.2.3 commentGenerator label

Look at the name , It's used to generate comments .

The default configuration :

    <commentGenerator >
        <property name="suppressAllComments" value="false"/>
        <property name="suppressDate" value="false"/>
        <property name="addRemarkComments" value="false"/>

suppressAllComments: Prevent comments from being generated , The default value is false.

suppressDate: Prevent generated comments from including timestamps , The default is false.

addRemarkComments: Add database comments to comments , The default is false.

And then there's us Can pass type Attribute specifies our custom annotation implementation class , Generate annotations we want . Custom implementation classes need to implement org.mybatis.generator.api.CommentGenerator.

 Recommended reading 
 Code comparison tool , I'll use this 6 individual 
 Share my favorite 5 A free online  SQL Database environment , It's so convenient !
Spring Boot A combination of three moves , Hand in hand to teach you to play elegant back-end interface 
MySQL 5.7 vs 8.0, You choose the one ? Net friend : I'm going to stay where I am ~

Last , I recommend you an interesting and interesting official account : The guy who wrote the code ,7 Old programmers teach you to write bug, reply interview | resources Send you a complete set of Development Notes There's a surprise

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云