As a Java backend developer, it is unavoidable to generate persistent object PO corresponding to database tables, interface DAO to operate database, and XML of CRUD, namely Mapper, in daily work.

Mybatis Generator Mybatis Generator is a code Generator provided by Mybatis official, which can be fully competent for this job. However, recently I tried Mybatis Generator provided by Mybatis -Plus official when developing “Programming cat” open source website, and found that the configuration is simpler. Development efficiency is higher! So to give small partners amicable wave.

Feel the joy of AutoGenerator generating code with a GIF.

Use Mybatis Generator

For contrast, let’s use Mybatis Generator to generate code and get a feel for the process.

First, add MySQL+MyBatis dependencies (preconditions for MyBatis Generator) to the PEM.xml file.

<! --> <dependency> <groupId> MySQL </groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <! <dependency> <groupId>org.mybatis.spring. Boot </groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 2.2.2 < / version > < / dependency >Copy the code

After adding, be sure to perform a Maven reload (see figure below) to ensure that MyBatis dependencies are loaded before performing step 2.

Otherwise, the next step may fail, but you won’t get any error messages. Don’t ask me why, the painful realization after stepping over the pit.

Once added, code can be generated either from the Maven plug-in or from Java code, as demonstrated here in the form of a Maven plug-in. The form of the Java code can refer to Mybatis Generator:

Mybatis.org/generator/r…

The second step is to add the MyBatis Generator plug-in to THE POP.xml. First, take a look at the overall structure diagram. Note that it is added under the build→plugins node.

First of all, MyBatis Generator plug-in, the latest version is 1.4.0, we use the last stable version 1.3.7, a little more stable.

<groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> The < version > 1.3.7 < / version >Copy the code

We use the configurationFile element to specify a configurationFile, mybatis-generator-config.xml:

<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
Copy the code

Take a look at the contents of mybatis-generator-config.xml.

<generatorConfiguration> <context id="myContext" targetRuntime="MyBatis3" defaultModelType="flat"> <! -- Comments --> <commentGenerator> <! < Property name="suppressAllComments" value="true"/> </commentGenerator> <! -- JDBC connection --> <jdbcConnection driverClass=" com.mysql.cj.jdbc.driver" connectionURL="jdbc:mysql://ip:3306/codingmoretiny02? useUnicode=true&amp; characterEncoding=utf-8&amp; serverTimezone=Asia/Shanghai&amp; useSSL=false" userId="codingmoretiny02" password="123456"> <! NullCatalogMeansCurrent =true--> <property name="nullCatalogMeansCurrent" value="true"/>  </jdbcConnection> <! JavaTypeResolver <property name="forceBigDecimals" value="true"/> </javaTypeResolver> <! <javaModelGenerator targetPackage="com.codingmore.mbg. Po "targetProject=" SRC /main/ Java "> <! <property name="trimStrings" value="true"/> </javaModelGenerator> <! -- generating Mapper. XML file - > < sqlMapGenerator targetPackage = "com. Codingmore. MBG. Mapper" targetProject = "SRC/main/resources" > </sqlMapGenerator> <! <javaClientGenerator targetPackage="com.codingmore.mbg.dao" targetProject=" SRC /main/ Java" type="XMLMAPPER"> </javaClientGenerator> <table schema="" tableName="user" domainObjectName="User" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false" selectByExampleQueryId="false"> </table> </context> </generatorConfiguration>Copy the code
  • The configuration file must contain at least one context
  • The commentGenerator is used to configure the generated comments
  • JdbcConnection is used to link databases
  • JavaTypeResolver Configures JDBC and Java type conversion rules
  • JavaModelGenerator configures the package path and project path generated by the Po
  • SqlMapGenerator Configures the directory generated by the mapper. XML file
  • JavaClientGenerator Configures the directory where mapper. Java files are generated
  • One table corresponds to one table. To generate multiple tables at the same time, you need to configure multiple tables

For more configuration information, see the following article:

Juejin. Cn/post / 684490…

Since database tables may change, we need to append a configuration

true
to allow the old files to be overwritten. To prevent the SQL statement we wrote from being overwritten, MyBatis Generator only overwrites old Po, DAOs, and *mapper.xml does not overwrite, but appends.

Mybatis Generator needs to link to the database, so you also need to add database driver dependencies like this:

<configuration>
</configuration>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
</dependency>
Copy the code

So it’s kind of redundant, because we added it before. Fortunately Maven provides includeCompileDependencies properties, can let we quote before adding in plug-in dependencies.

<includeCompileDependencies>true</includeCompileDependencies>
Copy the code

The mybatis -generator-Maven-plugin is configured as follows:

<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> < artifactId > mybatis generator - maven plugin - < / artifactId > < version > 1.3.7 < / version > < configuration > <configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile> <overwrite>true</overwrite><includeCompileDependencies>true</includeCompileDependencies> </configuration> </plugin> </plugins> </build>Copy the code

After the configuration is complete, you can double-click Mybatis Generator to run Maven. If there are no problems, you can see the generated file.

Use MyBatis-Plus AutoGenerator

MyBatis-Plus (short MP) is the enhancement tool of MyBatis. The official claim is that the relationship between MP and MyBatis is just like 1P and 2P in Contra, which can be described as good gay friends, the world goes.

AutoGenerator is a code generator launched by MyBatis-Plus, which can quickly generate the code of Entity, Mapper, Mapper XML, Service, Controller and other modules. More powerful and more efficient than Mybatis Generator.

Through the previous experience, I think you really feel the complexity of Mybatis Generator. Next, let’s experience the AutoGenerator. After comparison, you will have the answer in mind.

The first step is to add the AutoGenerator dependencies to the POM.xml file.

< the dependency > < groupId > com. Baomidou < / groupId > < artifactId > mybatis - plus - generator < / artifactId > < version > 3.4.1 track < / version > </dependency>Copy the code

MyBatis-Plus supports Velocity (default), Freemarker, Beetl, and the default Velocity engine is used here.

< the dependency > < groupId > org. Apache. Velocity < / groupId > < artifactId > velocity - engine - core < / artifactId > < version > 2.3 < / version >  </dependency>Copy the code

Step 3: Perform global configuration.

// Global configuration
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("Silent King II.");
gc.setOpen(false);
gc.setDateType(DateType.ONLY_DATE);
gc.setSwagger2(true);
gc.setIdType(IdType.AUTO);
Copy the code

Step 4, configure the data source.

// Data source configuration
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://ip:3306/codingmoretiny02? useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("codingmoretiny02");
dsc.setPassword("123456");
Copy the code

Step 5: Configure the package.

/ / package configuration
PackageConfig pc = new PackageConfig();
pc.setParent("top.codingmore.mpg");
Copy the code

More configuration items can be viewed at the official:

Baomidou.com/pages/06157…

Example code examples are as follows:

Public class CodeGenerator {public static void main(String[] args) {// AutoGenerator MPG = new AutoGenerator(); GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); SetAuthor (" The Silent King ii "); mpg.setGlobalConfig(gc); DataSourceConfig dsc = new DataSourceConfig(); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); mpg.setDataSource(dsc); mpg.execute(); }}Copy the code

SQL > alter database table (controller, service, Entity, mapper, etc.)

Third, summarize and compare

By comparing the Generator of Mybatis with the AutoGenerator of Mybatis -Plus, we can draw the following conclusion: The latter is simpler to configure, more efficient to develop, and more powerful — Mapper, Model, Service, Controller layer code can be generated quickly.

MyBatis-Plus really deserves Plus, it’s really good.

For a complete example, go to GitHub:

Github.com/itwanger/co…


This post has been adapted to GitHub’s 1.5K + Star open source column “The Path to Java Programmer Advancement”. This column is funny, easy to read, and extremely friendly and comfortable for Java enthusiasts 😄, The content includes but is not limited to Java foundation, Java Collection framework, Java IO, Java concurrent programming, Java virtual machine, Java enterprise development (Git, SSM, Spring Boot) and other core knowledge points.

Github.com/itwanger/to…

Star the repository and you have the potential to become a good Java engineer. Click the link below to jump to the Java Programmer’s Path to Progress website and start your fun learning journey.

tobebetterjavaer.com/

Nothing keeps me here but purpose, and though there are roses by the shore, and trees by the shore, and still harbours, I am not tied.