Mybatis Generator tool
After we start a new project, we usually have to write a lot of entity/pojo/dto/mapper/dao... Most of the R & D brothers will complain, why should I write CRUD repeatedly? In order to avoid writing some unnecessary repetitive code, this section introduces how to use an open-source tool to help us save from this simple and boring coding.
Welcome: MyBatis Mapper4
General Mapper can greatly facilitate developers. You can choose the general method according to your own needs at will, and you can also develop your own general method conveniently.
It is very convenient to use the addition, deletion, modification and query of MyBatis single table.
Single table operation is supported, and general multi table joint query is not supported.
General Mapper supports Mybatis-3.2.4 and above.
Tips:
All technical colleagues must have version awareness
Let's code!
Create mybatis-generator-tool Module
Reference resources Previous section Module in creates mybatis generator tool
- Add dependency
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>expensive-shop</artifactId> <groupId>com.life-runner</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>mybatis-generator-tool</artifactId> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <plugins> <!--springboot Build executable fat jars Necessary plug-ins, if not added, will have problems in the production environment--> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.6</version> <configuration> <!-- Set profile path --> <configurationFile> $/src/main/resources/generator/generatorConfig.xml </configurationFile> <!--overlays allowed--> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <!-- mysql8 drive--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <!--currency Mapper--> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>4.1.5</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
- Write profile
According to the path we specified in the pom file: $/src/main/resources/generator/generatorConfig.xml, we need to create the generator folder under the project SRC = > main = > resource directory, and create the file generatorConfig.xml under the folder, as follows:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> <generatorConfiguration> <!--Import database configuration content--> <properties resource="generator/config.properties"/> <context id="MysqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat"> <!--Configure whether to use universal Mapper Built in annotation extension, default true--> <!--<property name="useMapperCommentGenerator" value="false"/>--> <plugin type="tk.mybatis.mapper.generator.MapperPlugin"> <!--Set up Mapper Generated basic,Customizable--> <property name="mappers" value="tk.mybatis.mapper.common.Mapper"/> <!--Case sensitive--> <property name="caseSensitive" value="true"/> <!--Introduce lombok annotation--> <property name="lombok" value="Getter,Setter,ToString"/> <!--Separator definition--> <property name="beginningDelimiter" value="`"/> <property name="endingDelimiter" value="`"/> </plugin> <!-- Set database configuration --> <jdbcConnection driverClass="$" connectionURL="$" userId="$" password="$"> </jdbcConnection> <!-- Corresponding generated pojo Location package --> <javaModelGenerator targetPackage="com.liferunner.pojo" targetProject="src/main/java"/> <!-- Corresponding generated mapper Directory --> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <!-- To configure mapper Corresponding java mapping --> <javaClientGenerator targetPackage="com.liferunner.mapper" targetProject="src/main/java" type="XMLMAPPER"/> <!-- Database table --> <table tableName="carousel"></table> <table tableName="category"></table> <table tableName="items"></table> <table tableName="items_comments"></table> <table tableName="items_img"></table> <table tableName="items_param"></table> <table tableName="items_spec"></table> <table tableName="order_items"></table> <table tableName="order_status"></table> <table tableName="orders"></table> <table tableName="shop_users"></table> <table tableName="user_address"></table> <table tableName="users"></table> </context> </generatorConfiguration>
We can see a line of configuration content: < properties resource = "generator / config. Properties" / >, here is to externalize our database connection, account and other information. The configuration content is as follows:
jdbc.driverClass = com.mysql.cj.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/expensiveshop?characterEncoding=UTF-8&useSSL\ =false&useUnicode=true&serverTimezone=UTC jdbc.user = root jdbc.password = 12345678
You can see that the content set here is used in the subordinate code.
... <jdbcConnection driverClass="$" connectionURL="$" userId="$" password="$"> </jdbcConnection> ...
For configuration information, please refer to: Portal
- Test generation with maven
Execute the following command:
mybatis-generator-tool>mvn mybatis-generator:generate [INFO] Scanning for projects... [INFO] [INFO] ---------------< com.life-runner:mybatis-generator-tool >--------------- [INFO] Building mybatis-generator-tool 1.0-SNAPSHOT [INFO] --------------------------------[ jar ]--------------------------------- [INFO] [INFO] --- mybatis-generator-maven-plugin:1.3.6:generate (default-cli) @ mybatis-generator-tool --- [INFO] Connecting to the Database [INFO] Introspecting table carousel [INFO] Introspecting table category ... [INFO] Generating Record class for table carousel [INFO] Generating Mapper Interface for table carousel [INFO] Generating SQL Map for table carousel ... [INFO] Saving file CarouselMapper.xml ... [INFO] Saving file Carousel.java [INFO] Saving file Users.java ... [WARNING] Table configuration with catalog null, schema null, and table shop_users did not resolve to any tables [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 1.374 s [INFO] Finished at: 2019-11-05T15:40:07+08:00 [INFO] ------------------------------------------------------------------------
You can see that the execution is successful. Although the execution is successful here, when we open the file, we will find:
package com.liferunner.pojo; import java.util.Date; import javax.persistence.*; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString @Table(name = "Carousel") public class Carousel { /** * ����id �û�id */ @Id private String id; /** * �û��� �û��� */ private String imageUrl; ... }
There's a mess here. What's going on?
let's bing Portal , we can see 265000 results, which means that there are too many people who have met our problems. Click to open one:
We can see that the content in the red box is missing. Add < property name = "javafileencoding" value = "UTF-8" / > in the \ expense shop \ mybatis generator tool \ SRC \ main \ resources \ generator \ generatorconfig.xml, and execute the generation command again. You can see that our code is gone.
@Getter @Setter @ToString @Table(name = "`carousel`") public class Carousel { /** * Primary key */ @Id @Column(name = "`id`") private String id; /** * Picture address */ @Column(name = "`image_url`") private String imageUrl; ...
Tips:
In this part, I will thoroughly understand a bug first, otherwise I'm afraid that when you encounter it later, because it is really related to the generation of Common Mapper.
Click Users.java to see the following:
@Getter @Setter @ToString @Table(name = "users") public class Users { @Column(name = "USER") private String user; @Column(name = "CURRENT_CONNECTIONS") private Long currentConnections; @Column(name = "TOTAL_CONNECTIONS") private Long totalConnections; }
But our Users table is not like this. What's the matter???
Let's analyze:
1. Since we didn't use our own Users table, but it was generated by the generator, it is obvious that it must be a table in Mysql database, which is certain.
2. Then the question comes. Where did it come from? Find it, dish it.
3. Which database is it? sys? information_schema? performance_schema?
4. One by one, sure enough:
You can see that there is a users table in the performance ﹣ schema database, so are we generating it? Execute SHOW CREATE TABLE users, and the result is as shown in the figure above. The fields are consistent with the generated ones!
5. I've got it. How can I set it???
Simply modify JDBC: MySQL: / / localhost: 3306 / expensiveshop? Nullcatalogmeanscurrent = true & characterencoding = UTF-8 & usessl =False & useunicode = true & servertimezone = UTC, just add the bold part.
The literal meaning of nullCatalogMeansCurrent is very simple, that is to say, if it is null catalog, I will choose current. Because mysql does not support catalog, we need to tell mybatis this feature, and set it to true.
According to the interpretation of SQL standard, Catalog and Schema are abstract concepts in SQL environment, which are mainly used to solve the problem of naming conflict.
Conceptually, a database system contains multiple catalogs, each Catalog contains multiple schemas, and each Schema contains multiple database objects (tables, views, sequences, etc.). Conversely, a database object must belong to a Schema, and the Schema must belong to a Catalog, so we can get the fully qualified name of the database object from And the problem of naming conflicts is solved
From the perspective of implementation, the support and implementation of various database systems for Catalog and Schema are very different. For specific problems, it is necessary to refer to specific product specifications. The simple and common implementation is to use the database name as the Catalog name, and Oracle uses the user name as the Schema name
Please refer to the instructions on Mysql website: Portal
In this section, we have explained how to generate the simple and important repetitive work we want. We can implement it through tools. Next time, we will start to code the actual business
gogogo.