I have used a lot of code generators before. Here I record two commonly used code generators.
1, AutoGenerator
AutoGenerator is a self-contained code generator of mybatis plus. It is very powerful and can directly generate all table structures of the database at one time. However, each new table needs to overwrite the previously generated code, so I basically add a micro service for the first time, which will be used when designing the table structure, After that, the maintenance of services and the addition of functions will no longer cover this code.
Here you can look at the previous one in advance
Mybatis plus quick start
Spring boot integrates the use of swagger UI and swagger bootstrap UI
1.maven dependency
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
I added it based on the parent project. test and web are used here
Subproject
<dependencies> <!--mybatis-plus Persistent layer--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.3.1</version> </dependency> <!-- velocity template engine, Mybatis Plus Code generator needs --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency> <!--swagger--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <!--swagger ui--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <!--mysql Runtime dependency--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--lombok Used to simplify entity classes--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
2.CodeGenerator
Add a new class CodeGenerator in test
public class CodeGenerator { @Test public void genCode() { String prefix = ""; //Database prefix String moduleName = "edu"; //Database suffix------------------ // 1. Create code generator AutoGenerator mpg = new AutoGenerator(); // 2. Global configuration GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("taoL"); gc.setOpen(false); //Open Explorer after build // gc.setFileOverride(false); // Whether the file is overwritten during regeneration gc.setServiceName("%sService"); //Remove the initial I of the Service interface gc.setIdType(IdType.ASSIGN_ID); //Primary key policy gc.setDateType(DateType.ONLY_DATE);//Defines the date type in the generated entity class gc.setSwagger2(true);//Turn on Swagger2 mode mpg.setGlobalConfig(gc); // 3. Data source configuration DataSourceConfig dsc = new DataSourceConfig(); dsc.setUrl("jdbc:mysql://129.0.0.1:3306/" + prefix + "guli_" + moduleName + "?serverTimezone=GMT%2B8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("admin"); dsc.setPassword("admin"); dsc.setDbType(DbType.MYSQL); mpg.setDataSource(dsc); // 4. Package configuration PackageConfig pc = new PackageConfig(); pc.setModuleName(moduleName); //Module name pc.setParent("com.atguigu.guli.service"); pc.setController("controller"); pc.setEntity("entity"); pc.setService("service"); pc.setMapper("mapper"); mpg.setPackageInfo(pc); // 5. Policy configuration StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel);//Naming policy for mapping database tables to entities strategy.setTablePrefix(moduleName + "_");//Set table prefix not to generate strategy.setColumnNaming(NamingStrategy.underline_to_camel);//Naming policy for mapping database table fields to entities strategy.setEntityLombokModel(true); // lombok model @ accessories (chain = true) setter chain operation strategy.setLogicDeleteFieldName("is_deleted");//Delete field name logically strategy.setEntityBooleanColumnRemoveIsPrefix(true);//Remove Boolean is_ prefix //Auto fill TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT); TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE); ArrayList<TableFill> tableFills = new ArrayList<>(); tableFills.add(gmtCreate); tableFills.add(gmtModified); strategy.setTableFillList(tableFills); strategy.setRestControllerStyle(true); //restful api style controller strategy.setControllerMappingHyphenStyle(true); //Hump to hyphen in url mpg.setStrategy(strategy); // 6. Execute mpg.execute(); } }
In this way, three layers of code are generated, and the annotation of swagger is added to the entity class.
But although this method is very cool, it will generate all every time. Of course, it can also be GC setFileOverride(false); Set do not overwrite, so that when a new table is added to the database, only the new table can be generated, and the original modified logic code will not be overwritten.
However, it is still impossible to specify a table to generate code.
2, generatorConfiguration
This is the most original reverse engineering officially recommended by mybatis, which only automatically generates xml of entity and dao layer according to table name. However, the addition, deletion, modification and query of this part is also the most repetitive work, generating the most basic template. Other business functions are basically our own defined functions.
1.maven
<!--This dependency already includes JDBC rely on generator+mybatis--> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.0</version> </dependency>
<build> <plugins> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.7</version> <configuration> <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> </dependencies> </plugin> </plugins> </build>
2.generatorConfig.xml
Add generatorconfig. Under the resources folder XML file
<?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> <context id="MySQL2Tables" targetRuntime="MyBatis3" defaultModelType="flat"> <commentGenerator> <property name="suppressDate" value="true" /> <property name="suppressAllComments" value="true" /> </commentGenerator> <!--Database link address account password --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/guli_edu?useSSL=false" userId="admin" password="admin"> </jdbcConnection> <!-- true: use BigDecimal corresponding DECIMAL and NUMERIC data type --> <!-- false: default, scale>0;length>18: use BigDecimal; scale=0;length[10,18]: use Long; scale=0;length[5,9]: use Integer; scale=0;length<5: use Short; --> <javaTypeResolver type="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl"> <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!--generate Model Class storage location --> <javaModelGenerator targetPackage="com.atguigu.guli.service.edu.entity" targetProject="src/main/java"> <!-- stay targetPackage Based on the database schema Regenerate into a layer package,The final generated class is placed in this package By default false --> <property name="enableSubPackages" value="true" /> <!-- Set whether to getter Method, right String Type field call trim()method --> <property name="trimStrings" value="true" /> <!-- for MyBatis3/MyBatis3Simple Automatically create a constructor for each generated class. The constructor contains all the field;Instead of using setter; --> <property name="constructorBased" value="false" /> <!-- for MyBatis3/MyBatis3Simple Whether to create an immutable class. If yes true, that MBG Will create one without setter Method, replaced by a class similar to constructorBased Class of --> <property name="immutable" value="false" /> </javaModelGenerator> <!--Storage location of generation mapping file --> <sqlMapGenerator targetPackage="mappers" targetProject="src/main/resources/mapper_mysql"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!--generate Dao Class storage location --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.guli.service.edu.dao" targetProject="src/main/java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!--Generate corresponding table and class name --> <table tableName="edu_teacher" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <property name="useActualColumnNames" value="true" /> <!-- To return the primary key value when inserting, please open this property, column List with value as primary key --> <generatedKey column="id" sqlStatement="MySql" identity="true" /> </table> </context> </generatorConfiguration>
When running, add maven module and generator as shown in the screenshot. When running edit, add maven module and generator
Click Run. Note that each run will overwrite the previous code. Be careful in the actual operation of the project. Just add a table tableName to replace it.