The environment
Springboot 2.2.6.RELEASE Mybatis -plus 3.3.0 Spring-boot-starter-swagger 1.5.1.RELEASE
- The environment version better be consistent, otherwise, you can get some unexpected surprises
In actual combat
- If you are not clear about how to store the file, please refer to my structure
SQL script
/* Navicat Premium Data Transfer Source Server: 50722 Source Host : localhost:3306 Source Schema : pro Target Server Type : MySQL Target Server Version : 50722 File Encoding : 65001 Date: 05/04/2020 19:17:01 */
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(111) NOT NULL AUTO_INCREMENT COMMENT 'number',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'name',
`age` int(11) NULL DEFAULT NULL COMMENT 'age'.PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES (1.'President'.18);
INSERT INTO `student` VALUES (2.'Lao wang'.20);
INSERT INTO `student` VALUES (3.'The King of Lanling'.11);
SET FOREIGN_KEY_CHECKS = 1;
Copy the code
pom.xml
<? The 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 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > 4.0.0 < / modelVersion > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.2.6. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.cxyxs</groupId> <artifactId>auto</artifactId> <version>0.0.1 -snapshot </version> <name>auto</name> <description>Demo project for Spring Boot</description> <properties> < Java version > 1.8 < / Java version > < / properties > < dependencies > <! -- Web dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! Boot </groupId> <artifactId> Spring-boot-starter-test </artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> < artifactId > mybatis - plus - the boot - starter < / artifactId > < version > 3.3.0 < / version > < / dependency > <! <dependency> <groupId>com.baomidou</groupId> < artifactId > mybatis - plus - generator < / artifactId > < version > 3.3.1. TMP < / version > < / dependency > <! <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> The < version > 2.2 < / version > < / dependency > <! <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> The < version > 8.0.18 < / version > < / dependency > <! Alibaba </groupId> <artifactId>druid</artifactId> The < version > 1.1.6 < / version > < / dependency > <! > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <! --swagger2--> <dependency> <groupId>com.spring4all</groupId> <artifactId>spring-boot-starter-swagger</artifactId> <version>1.5.1.RELEASE</version> </dependency> </dependencies> <build> <! Codeauto </finalName> <! <resources> <resource> <directory> SRC /main/resources</directory> <includes> <include>**/*</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src\main\java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <! Plugins </groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>com.cxyxs.auto.AutoApplication</mainClass> </manifest> </archive> </configuration> </plugin> <! Plugins </groupId> org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions> </plugin> <! Plugins </groupId> org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build> </project>Copy the code
- MyBatis-Plus removed the default dependencies between code generators and template engines after 3.0.3, requiring manual addition of dependencies:
- Swagger is integrated to facilitate the front and back end docking
- Can achieve jar package, build directly on the line, build inside the configuration, is to hit jar package
application.yml
Server: port: 8888 Spring: datasource: # driver-class-name: com.mysql.cj.jdbc.driver # druid connection pool type: Com. Alibaba. Druid. Pool. DruidDataSource url: JDBC: mysql: / / 127.0.0.1:3306 / pro? useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT % 2 b8 username: root password: root # # # increase the log output, convenient location problem logging: level: root: warn com. Cxyxs. Mybatisplus. Dao: Mybatis: '%p%m%n' mybatis-plus: mapper-locations: The classpath * : / com/cxyxs/auto/mapper/XML / *. XML global - config: db - config: # # # logic does not delete the value of the logic - not - delete - value: Logic-delete-value: 1 #### Scan swagger notes Swagger: base-package: com.cxyxsCopy the code
- Configure the database information
- Mapper-locations are defined according to a rule that automatically generates code
- Swagger configuration Swagger annotation, scan range
Start the class
package com.cxyxs.auto;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.cxyxs.auto.mapper")
@EnableSwagger2Doc
public class AutoApplication {
public static void main(String[] args) { SpringApplication.run(AutoApplication.class, args); }}Copy the code
- @mapperscan configure the location of the scanned DAO package (in our common thinking). The president used to name it after Mapper
- @enablesWagger2doc EnableSwagger annotation
Automatic code generation
package com.cxyxs.auto;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/** * Description: * Author: wude * Date: 2020/4/5 9:14 * Modified By: */
@RunWith(SpringRunner.class)
@SpringBootTest
public class CodeGenerationTests {
public static void main(String[] args) {
// Code generator
AutoGenerator mpg = new AutoGenerator();
// Global configuration
GlobalConfig gc = new GlobalConfig();
// Current path
String projectPath = System.getProperty("user.dir");
// Output path
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(The Society of Procedural Apes); // Set the author
// Whether to open the folder after generating the code
gc.setOpen(false);
gc.setFileOverride(false); // Whether to override the original code, I recommend setting it to false, do not override, the risk factor is too high
gc.setServiceName("%sService"); // Drop the I prefix of service
/* gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); * /
gc.setDateType(DateType.ONLY_DATE); // Date format
gc.setSwagger2(true); // Entity attribute Swagger2 annotation, add comment to entity class
mpg.setGlobalConfig(gc);
// Data source configuration
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("JDBC: mysql: / / 127.0.0.1:3306 / pro? useUnicode=true&characterEncoding=utf8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT %2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL); // Specify the type of the database
mpg.setDataSource(dsc);
/ / package configuration
PackageConfig pc = new PackageConfig();
pc.setParent("com.cxyxs.auto"); // Customize the package path
//pc.setModuleName("module"); // Com.cxyxs.test. module will be generated after the module name is set, which contains the mapper set previously,entity
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
// Policy configuration
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("student"); // Set the name of the mapping table
// set table prefix to cxyxs_student
//strategy.setTablePrefix(new String[]{"cxyxs_"});
// Package naming rules, using the hump rule
strategy.setNaming(NamingStrategy.underline_to_camel);
// Column name, using the hump rule
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// Whether to use Lombok
strategy.setEntityLombokModel(true);
// Name the hump
strategy.setRestControllerStyle(true);
strategy.setLogicDeleteFieldName("is_delete"); // Logical delete
// Automatic fill field, in the project development process, such as create time, modify time, every time we need to specify, too difficult, set to automatic fill rule, do not need to assign value
TableFill fillInsert = new TableFill("create_time", FieldFill.INSERT);
TableFill fillUpdate= new TableFill("update_time", FieldFill.UPDATE);
List fillLists = new ArrayList();
fillLists.add(fillInsert);
fillLists.add(fillUpdate);
strategy.setTableFillList(fillLists);
/ / optimistic locking
//strategy.setVersionFieldName("version");
mpg.setStrategy(strategy);
mpg.execute(); / / execution}}Copy the code
Launch the main method directly and it’s time to witness the magic.
Contoller, Entity, Mapper,service code generated for us.
- Swagger comments are generated for us, and the code is very standard, let us write, may encounter a lot of very low-level errors.
- Although automatic code generation is very intelligent, the premise of intelligence is standardized, database commands, the highest compliance with the relevant specifications, but here more elaborated
The controller class
package com.cxyxs.auto.controller;
import com.cxyxs.auto.entity.Student;
import com.cxyxs.auto.mapper.StudentMapper;
import com.cxyxs.auto.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/** ** <p> * Front-end controller * </p> **@authorProgramming Ape Society *@sinceThe 2020-04-05 * /
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentMapper studentMapper;
@GetMapping("/test")
@ApiOperation(value = "Test interface",notes = "Test")
public List<Student> getStudent1(Student stu){
List<Student> lists = studentMapper.selectList(null);
returnlists; }}Copy the code
- StudentController class, which is automatically generated, add a method and see what happens.
test
http://localhost:8888/swagger-ui.html
You can find a basic-error-controller on the page. Actually, there is no definition of this in our code. If you have obsessive-compulsive disorder, you can solve it by Baidu.
Through the visual interface, the front end can see the returned parameter comments
- There is also a comment on the pass
Click the try it Out button
There are comments on the pass and return parameters that need to be connected to the front end, and that interface, what it does, has a comment document. So there’s nothing going on backstage