源码地址:https://github.com/nongzihong/automatic
MyBatis-Plus 官网:https://mp.baomidou.com/
dao,entity,service,controller都要自己去编写。而这部分代码,都是有一定的规范,有需求,就有对应的产品应运而生,AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
springboot 2.2.1.RELEASE
mybatis-plus 3.3.0
spring-boot-starter-swagger 1.5.1.RELEASE
项目结构图
create database pro;
use pro;
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 '编号',
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '姓名',
`age` int(11) NULL DEFAULT NULL COMMENT '年龄',
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, '社长', 18);
INSERT INTO `student` VALUES (2, '老王', 20);
INSERT INTO `student` VALUES (3, '兰陵王', 11);
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.1.RELEASE
com.example
automatic
0.0.1-SNAPSHOT
automatic
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.3.0
com.baomidou
mybatis-plus-generator
3.3.1.tmp
org.projectlombok
lombok
true
org.apache.velocity
velocity-engine-core
2.2
com.alibaba
druid
1.1.6
org.springframework.boot
spring-boot-devtools
true
com.spring4all
spring-boot-starter-swagger
1.5.1.RELEASE
org.mariadb.jdbc
mariadb-java-client
2.3.0
codeauto
src/main/resources
**/*
true
src\main\java
**/*.xml
org.springframework.boot
spring-boot-maven-plugin
org.apache.maven.plugins
maven-jar-plugin
true
lib/
com.example.automatic.AutoApplication
org.apache.maven.plugins
maven-surefire-plugin
true
server:
port: 8888
spring:
datasource:
# 配置数据源
driver-class-name: org.mariadb.jdbc.Driver
# 使用druid连接池
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mariadb://127.0.0.1:3306/pro
username: root
password: 123
###增加日志输出,方便定位问题
logging:
level:
root : warn
com.cxyxs.mybatisplus.dao: trace
###控制台输出格式
pattern:
console: '%p%m%n'
mybatis-plus:
mapper-locations: classpath*:/com/example/automatic/mapper/xml/*.xml
global-config:
db-config:
###逻辑未删除的值
logic-not-delete-value: 0
###逻辑已删除的值
logic-delete-value: 1
####扫描swagger注解
swagger:
base-package: com.example
package com.example.automatic;
import com.spring4all.swagger.EnableSwagger2Doc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@MapperScan("com.example.automatic.mapper")
@SpringBootApplication
@EnableSwagger2Doc
public class AutomaticApplication {
public static void main(String[] args) {
SpringApplication.run(AutomaticApplication.class, args);
}
}
package com.example.automatic;
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;
@SpringBootTest
@RunWith(SpringRunner.class)
class CodeGenerationTests {
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");
gc.setAuthor("ZH"); //设置作者
//生成代码后,是否打开文件夹
gc.setOpen(false);
gc.setFileOverride(false); //是否覆盖原来代码,个人建议设置为false,别覆盖,危险系数太高
gc.setServiceName("%sService"); //去掉service的I前缀,一般只需要设置service就行
gc.setDateType(DateType.ONLY_DATE); //日期格式
gc.setSwagger2(true); // 实体属性 Swagger2 注解,实体类上会增加注释
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mariadb://127.0.0.1:3306/pro");
// dsc.setSchemaName("public");
dsc.setDriverName("org.mariadb.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123");
dsc.setDbType(DbType.MYSQL); //指定数据库的类型
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example.automatic"); //自定义包的路径
//pc.setModuleName("module"); //模块名称 设置后,会生成com.example.automatic,里面存放之前设置的mapper,entity
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("student"); //设置映射的表名,可以设置多个表
//表前缀设置 cxyxs_student
//strategy.setTablePrefix(new String[]{"cxyxs_"});
//包的命名规则,使用驼峰规则
strategy.setNaming(NamingStrategy.underline_to_camel);
//列的名称,使用驼峰规则
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//是否使用lombok
strategy.setEntityLombokModel(true);
//驼峰命名
strategy.setRestControllerStyle(true);
strategy.setLogicDeleteFieldName("is_delete"); //逻辑删除,假删除会用到
//自动填充字段,在项目开发过程中,例如创建时间,修改时间,每次,都需要我们来指定,太麻烦了,设置为自动填充规则,就不需要我们赋值咯
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);
//乐观锁
//strategy.setVersionFieldName("version");
mpg.setStrategy(strategy);
mpg.execute(); //执行
}
}
contoller,entity,mapper,service代码都给我们生成好
package com.example.automatic.controller;
import com.example.automatic.entity.Student;
import com.example.automatic.mapper.StudentMapper;
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;
/**
*
* 前端控制器
*
*
* @author ZH
* @since 2020-04-08
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentMapper studentMapper;
@GetMapping("/test")
@ApiOperation(value = "测试接口", notes = "测试")
public List getStudent1(Student stu) {
List lists = studentMapper.selectList(null);
studentMapper.selectByMap();
return lists;
}
@GetMapping("/count")
@ApiOperation(value = "统计数量", notes = "测试")
public int getCount(){
return studentMapper.count();
}
}
StudentController这个类,是自动生成的,增加两个个方法,来看看效果。
http://localhost:8888/swagger-ui.html
通过页面可以发现有一个basic-error-controller,实际上,我们代码里面没有定义这个,有强迫症的,可以百度解决方法,配置一下,这里就不配置了
通过可视化界面,前端可以看到返回的参数注释
传参也有注释
点击try it out按钮 可以看到有返回数据