MyBatis-Plus is a framework that we often use during development. It often needs to be configured when developing Springboot projects. Correct use can indeed reduce a lot of workload for us, so that we no longer have to build entities one by one based on the database. Class. Record it here
MyBatis-Plus integration
-
Add the following MyBatis dependencies
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.3.1</version> </dependency>
Replace with
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency>
It turns out that you can just add it directly without using Mybatis.
-
The configuration of the data source is the same as MyBatis, but the following configuration is added to the yml file:
mybatis-plus: mapper-locations: classpath:mapper/*.xml configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: banner: true enableSqlRunner: true type-aliases-package: com.zwl.entity
-
After completing the above, it is actually configured and there is no problem. If you need to test, you need to create a new Service, etc. It is strongly recommended to follow the steps below to automatically generate related Services and Entities.
MyBatis-Plus-Generator automatically generates code
- Add the following dependencies
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.5.3.1</version> </dependency> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
-
Follow up on your own situation, modify the code below and run it to automatically generate Service, Dao and other related files.
package com.breed.livestock.generator; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.config.TemplateType; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.converts.PostgreSqlTypeConvert; import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery; import com.baomidou.mybatisplus.generator.config.querys.PostgreSqlQuery; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import com.baomidou.mybatisplus.generator.fill.Column; import com.baomidou.mybatisplus.generator.fill.Property; import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler; import com.baomidou.mybatisplus.generator.keywords.PostgreSqlKeyWordsHandler; import java.util.Collections; // Code automatic generator public class Generator {<!-- --> // Database connection field configuration private static final String JDBC_URL = "jdbc:postgresql://localhost:5432/test2?characterEncoding=utf-8 & amp;serverTimezone=GMT+8 & amp;useSSl=true"; private static final String JDBC_USER_NAME = "postgres"; private static final String JDBC_PASSWORD = "postgres"; // Package name and module name private static final String PACKAGE_NAME = "com.breed.livestock"; private static final String MODULE_NAME = "livestock"; //Table name, multiple tables should be separated by English commas private static final String[] TBL_NAMES = {<!-- -->"sys_department","sys_role","sys_user"}; //The prefix of the table name, the prefix will be removed when generating code from the table private static final String TABLE_PREFIX = ""; public static void main(String[] args) {<!-- --> //Get the current project path (no need to modify here) String projectPath = System.getProperty("user.dir"); /** * 1. Database configuration (set data source) Configure database connection and fields to be used The PG database is configured here. If it is MySQL, it needs to be modified. */ DataSourceConfig.Builder dataSourceConfigBuilder = new DataSourceConfig.Builder(JDBC_URL, JDBC_USER_NAME, JDBC_PASSWORD) .dbQuery(new PostgreSqlQuery()) .typeConvert(new PostgreSqlTypeConvert()) .keyWordsHandler(new PostgreSqlKeyWordsHandler()); FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(dataSourceConfigBuilder); /** * 2. Global configuration */ fastAutoGenerator.globalConfig( globalConfigBuilder -> globalConfigBuilder .fileOverride() // Overwrite the generated file .disableOpenDir() // Do not open the generated file directory .outputDir(projectPath + "/src/main/java") //Specify the output directory, pay attention to the slash .author("hanbo") //Set the author of the comment .commentDate("yyyy-MM-dd HH:mm:ss") //Set the date format of the comment .dateType(DateType.TIME_PACK) // Use the new time type in java8 // .enableSwagger() // Open swagger document ); /** Date type DateType DateType.ONLY_DATE uses Date under the java.util.date package DateType.SQL_PACK uses Date under the java.sql package DateType.TIME_PACK is only supported by jdk1.8 or above because it uses java.time.LocalDateTime (recommended) */ /** * 3.Package configuration */ fastAutoGenerator.packageConfig( packageConfigBuilder -> packageConfigBuilder .parent(PACKAGE_NAME) //Set the parent package name // .moduleName(MODULE_NAME) // Set the parent package module name .entity("entity") //Set the package name of each module under MVC .mapper("mapper") .service("service") .serviceImpl("service.impl") .controller("controller") .xml( "\src\main\resources\mapper") // Set the directory of XML resource files .pathInfo(Collections.singletonMap(OutputFile.xml, projectPath + "\src\main\resources\mapper"))// Set the directory of XML resource files ); /** * 4. Strategy configuration */ fastAutoGenerator.strategyConfig( strategyConfigBuilder -> strategyConfigBuilder .enableCapitalMode() // Enable uppercase naming .enableSkipView() // Enable skip view .disableSqlFilter() // Disable sql filtering .addInclude(TBL_NAMES) //Set the table name to be generated .addTablePrefix(TABLE_PREFIX) //Set the filter table prefix ); /** * 4.1 Entity policy configuration */ fastAutoGenerator.strategyConfig( strategyConfigBuilder -> strategyConfigBuilder.entityBuilder() .enableTableFieldAnnotation() // Generate field annotations when generating entities, including @TableId annotations, etc. --- .naming(NamingStrategy.underline_to_camel) // Naming strategy for mapping database tables and fields to entities, converting underscores to camel case .columnNaming(NamingStrategy.underline_to_camel) .idType(IdType.AUTO) // The global primary key type is AUTO (auto-increment) .enableLombok() //Support lombok to enable annotations .logicDeleteColumnName("deleted") // Logically deleted field name (database) .logicDeletePropertyName("deleted") // Logically deleted property name (entity) .addTableFills(new Column("create_time", FieldFill.INSERT)) // Automatic fill configuration create_time update_time two ways .addTableFills(new Property("updateTime", FieldFill.INSERT_UPDATE)) .versionColumnName("version") // Turn on optimistic locking .disableSerialVersionUID() // Disable generation of serialVersionUID, default value: true .enableChainModel() // Enable entity class chain programming .formatFileName("%sEntity") // The entity name is formatted as XXXEntity formatFileName("%sEntity") .enableTableFieldAnnotation() .enableFileOverride() ); /** * 4.2 Controller policy configuration */ fastAutoGenerator.strategyConfig( strategyConfigBuilder -> strategyConfigBuilder.controllerBuilder() .enableRestStyle() // Enable generating @RestController controller .enableHyphenStyle() // Enable camel case to hyphen localhost:8080/hello_id_2 ); /** * 4.3 Service policy configuration Format the file name of the service interface and implementation class, remove the I ---- in front of the default ServiceName */ fastAutoGenerator.strategyConfig( strategyConfigBuilder -> strategyConfigBuilder.serviceBuilder() .formatServiceFileName("I%sService") .formatServiceImplFileName("%sServiceImpl")); /** * 4.4 Mapper strategy configuration Format mapper file name, format xml implementation class file name */ fastAutoGenerator.strategyConfig( strategyConfigBuilder -> strategyConfigBuilder.mapperBuilder() .enableMapperAnnotation() // Enable @Mapper annotation .formatMapperFileName("%sMapper") .formatXmlFileName("%sMapper")); /** 5. Generate code * */ // fastAutoGenerator.templateEngine(new FreemarkerTemplateEngine()) // Use Freemarker engine template, the default is Velocity engine template fastAutoGenerator.execute(); } }