1、定义
AutoGenerator是MyBatis-Plus的代码生成器,通过AutoGenerator可以快速生成Entity、Mapper、Mapper XML、Service、Controller等各个模块的代码,极大的提升了开发效率。
2、简单实例
(1)目录
(2)MySpringBootApplication.java
package cn.hwd.generator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import cn.hwd.generator.service.CodeGenerator;
@SpringBootApplication
public class MySpringBootApplication implements CommandLineRunner {
@Autowired
CodeGenerator codeGenerator;
public static void main(String[] args) throws Exception {
SpringApplication.run(MySpringBootApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
codeGenerator.exec();
}
}
(3)CodeGenerator.java
package cn.hwd.generator.service;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
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.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
@Service
public class CodeGenerator {
String controllerName = "UserController";
String serviceName = "UserService";
String entityName = "User";
String url = "jdbc:mysql://127.0.0.1:3306/hwd?useUnicode=true&characterEncoding=UTF-8&useSSL=false";
String driverName = "com.mysql.jdbc.Driver";
String username = "root";
String password = "mysql";
String moduleName = "generator";
String parent = "cn.hwd";
String include = "t_user";
String tablePrefix = "t_";
String tableName = "t_user";
String pojoObjectName = "user";
String serviceObjectName = "userService";
public void exec() {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setFileOverride(true);
gc.setOpen(false);
gc.setDateType(DateType.ONLY_DATE);
gc.setControllerName(controllerName);
gc.setServiceName(serviceName);
gc.setEntityName(entityName);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
dsc.setDriverName(driverName);
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(moduleName);
pc.setParent(parent);
mpg.setPackageInfo(pc);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
templateConfig.setController("/templates/controller.java.vm");
templateConfig.setEntity("/templates/entity.java.vm");
templateConfig.setMapper(null);
templateConfig.setService("/templates/service.java.vm");
templateConfig.setServiceImpl(null);
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 自定义属性注入
InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
Map map = new HashMap<>();
map.put("tableName", tableName);
map.put("pojoObjectName", pojoObjectName);
map.put("serviceObjectName", serviceObjectName);
this.setMap(map);
}
};
//配置自定义属性注入
mpg.setCfg(injectionConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setInclude(include);
strategy.setTablePrefix(tablePrefix);
mpg.setStrategy(strategy);
mpg.execute();
}
}
(4)controller.java.vm
package ${package.Controller};
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
@RestController
@RequestMapping("")
public class ${table.controllerName} {
@Autowired
${table.serviceName} ${cfg.serviceObjectName};
@RequestMapping(value = "", method = RequestMethod.GET)
public List<${entity}> find() {
return ${cfg.serviceObjectName}.find();
}
}
(5)entity.java.vm
package ${package.Entity};
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class ${entity} {
#foreach($field in ${table.fields})
@JsonProperty
#if(${field.propertyType.equals("Date")})
@JsonFormat(pattern="yyyyMMddHHmmssSSS", timezone="GMT+8")
#end
${field.propertyType} ${field.propertyName};
#end
}
(6)service.java.vm
package ${package.Service};
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import cn.hwd.generator.entity.User;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class ${table.serviceName} {
@Autowired
JdbcTemplate jdbcTemplate;
public List<${entity}> find() {
String sql = "SELECT * FROM ${cfg.tableName}";
log.info(sql);
return jdbcTemplate.query(sql, new RowMapper<${entity}>() {
@Override
public ${entity} mapRow(ResultSet rs, int rowNum) throws SQLException {
${entity} ${cfg.pojoObjectName} = new ${entity}();
#foreach($field in ${table.fields})
#if(${field.propertyType.equals("Date")})
${cfg.pojoObjectName}.set${field.propertyName}(rs.getTimestamp("${field.propertyName}"));
#elseif(${field.propertyType.equals("Integer")})
${cfg.pojoObjectName}.set${field.propertyName}(rs.getInt("${field.propertyName}"));
#elseif(${field.propertyType.equals("String")})
${cfg.pojoObjectName}.set${field.propertyName}(rs.getString("${field.propertyName}"));
#elseif(${field.propertyType.equals("Double")})
${cfg.pojoObjectName}.set${field.propertyName}(rs.getDouble("${field.propertyName}"));
#end
#end
return ${cfg.pojoObjectName};
}
});
}
}
(7)application.properties
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hwd?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=mysql
(8)build.gradle
buildscript {
ext {
springBootVersion = '1.5.16.RELEASE'
}
repositories {
maven {
name 'generator repository'
url 'http://maven.aliyun.com/nexus/content/groups/public/'
}
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'cn.hwd.generator'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
maven {
name 'generator repository'
url 'http://maven.aliyun.com/nexus/content/groups/public/'
}
mavenCentral()
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
springBoot{
executable=true
}
dependencies {
compile('org.springframework.boot:spring-boot-starter')
compile('org.springframework.boot:spring-boot-starter-web')
compile('com.baomidou:mybatis-plus-boot-starter:3.0.6')
compile('org.apache.velocity:velocity-engine-core:2.0')
compile('org.json:json')
runtime('mysql:mysql-connector-java')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
3、运行结果
生成了3个文件,分别是UserController.java、UserService.java和User.java
(1)UserController.java
package cn.hwd.generator.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import cn.hwd.generator.entity.User;
import cn.hwd.generator.service.UserService;
@RestController
@RequestMapping("")
public class UserController {
@Autowired
UserService userService;
@RequestMapping(value = "", method = RequestMethod.GET)
public List find() {
return userService.find();
}
}
(2)UserService.java
package cn.hwd.generator.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import cn.hwd.generator.entity.User;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class UserService {
@Autowired
JdbcTemplate jdbcTemplate;
public List find() {
String sql = "SELECT * FROM t_user";
log.info(sql);
return jdbcTemplate.query(sql, new RowMapper() {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("Id"));
user.setName(rs.getString("Name"));
user.setAge(rs.getInt("Age"));
user.setBirth(rs.getTimestamp("Birth"));
user.setWeight(rs.getDouble("Weight"));
return user;
}
});
}
}
(3)User.java
package cn.hwd.generator.entity;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class User {
@JsonProperty
Integer Id;
@JsonProperty
String Name;
@JsonProperty
Integer Age;
@JsonProperty
@JsonFormat(pattern="yyyyMMddHHmmssSSS", timezone="GMT+8")
Date Birth;
@JsonProperty
Double Weight;
}
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.5.16.RELEASE)
2019-11-28 15:36:20.103 INFO 13516 --- [ main] c.hwd.generator.MySpringBootApplication : Starting MySpringBootApplication on LAPTOP-N1UHE4RC with PID 13516 (D:\workspace\work\test\generator\bin started by vineg in D:\workspace\work\test\generator)
2019-11-28 15:36:20.106 INFO 13516 --- [ main] c.hwd.generator.MySpringBootApplication : No active profile set, falling back to default profiles: default
2019-11-28 15:36:20.169 INFO 13516 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@f736069: startup date [Thu Nov 28 15:36:20 CST 2019]; root of context hierarchy
2019-11-28 15:36:21.052 WARN 13516 --- [ main] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[cn.hwd.generator]' package. Please check your configuration.
2019-11-28 15:36:22.805 INFO 13516 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-11-28 15:36:22.838 INFO 13516 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-11-28 15:36:22.838 INFO 13516 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.34
2019-11-28 15:36:23.040 INFO 13516 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-11-28 15:36:23.041 INFO 13516 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2875 ms
2019-11-28 15:36:23.231 INFO 13516 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2019-11-28 15:36:23.235 INFO 13516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-11-28 15:36:23.236 INFO 13516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-11-28 15:36:23.236 INFO 13516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-11-28 15:36:23.236 INFO 13516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-11-28 15:36:23.649 INFO 13516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@f736069: startup date [Thu Nov 28 15:36:20 CST 2019]; root of context hierarchy
2019-11-28 15:36:23.741 INFO 13516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-11-28 15:36:23.742 INFO 13516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-11-28 15:36:23.796 INFO 13516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-11-28 15:36:23.796 INFO 13516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-11-28 15:36:23.849 INFO 13516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
_ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\
/ |
3.0.6
2019-11-28 15:36:24.944 INFO 13516 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-11-28 15:36:24.986 INFO 13516 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2019-11-28 15:36:25.462 INFO 13516 --- [ main] c.hwd.generator.MySpringBootApplication : Started MySpringBootApplication in 5.718 seconds (JVM running for 6.356)