- SpringBoot整合MybatisGenerator
- springboot,整合mybatisgenerator
- springboot mybatisGenerator只需几步快
- springboot整合springsecurity从Hello
- springboot整合springsecurity从Hello
- springboot整合springsecurity从Hello
- SpringBoot + Shiro 整合 JWT
- springboot整合springsecurity从Hello
- springboot整合ehcache,使用httpClient
- SpringBoot整合Elasticsearch报错avail
依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--MyBatis分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.10</version>
</dependency>
<!--集成druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- MyBatis 生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.3</version>
</dependency>
application.properties
server.port=8046
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.mapper-locations=classpath:mapping/*Mapper.xml
mybatis.type-aliases-package=com.example.entity
generatorConfig.xml
<?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>
<properties resource="application-dev.properties"/>
<context id="MySqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="javaFileEncoding" value="UTF-8"/>
<!-- 为模型生成序列化方法-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="com.example.sprngbootdemo.util.LombokPlugin"/>
<!--可以自定义生成model的代码注释-->
<commentGenerator type="com.example.sprngbootdemo.util.CommentGenerator">
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<property name="suppressDate" value="true"/>
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<!--配置数据库连接-->
<jdbcConnection driverClass="${spring.datasource.driver-class-name}"
connectionURL="${spring.datasource.url}"
userId="${spring.datasource.username}"
password="${spring.datasource.password}">
<!--解决mysql驱动升级到8.0后不生成指定数据库代码的问题-->
<property name="nullCatalogMeansCurrent" value="true"/>
</jdbcConnection>
<!--生成entity类存放位置-->
<javaModelGenerator targetPackage="com.example.sprngbootdemo.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件存放位置-->
<sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--指定生成mapper接口的的路径-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.sprngbootdemo.mapper"
targetProject="src/main/java"/>
<!--生成全部表tableName设为%-->
<table tableName="admin">
<generatedKey column="id" sqlStatement="MySql" identity="true"/>
<!-- 数据库TIMESTAMP类型改成对应java的LocalDateTime类型-->
<columnOverride jdbcType="TIMESTAMP" javaType="java.time.LocalDateTime" column="create_time"/>
<columnOverride jdbcType="TIMESTAMP" javaType="java.time.LocalDateTime" column="update_time"/>
</table>
</context>
</generatorConfiguration>
MyBatisConfig
@Configuration
@MapperScan("com.example.sprngbootdemo.mapper")
public class MyBatisConfig {
}
CommentGenerator
public class CommentGenerator extends DefaultCommentGenerator {
//添加注释总开关,generator.xml中设置为true!!!
private boolean addRemarkComments = false;
//是否需要添加swaggerui注释
private boolean addSwaggerUi = true;
//是否需要添加顶部作者姓名和创建时间
private boolean addAuthorAndDate = true;
//是否需要Lombok添加@Data注释
private boolean addLombok = true;
private Properties properties;
private static final String LOMBOK_DATA = "lombok.Data";
private static final String ACCESSORS = "lombok.experimental.Accessors";
private static final String JSON_FORMAT = "com.fasterxml.jackson.annotation.JsonFormat";
private static final String EXAMPLE_SUFFIX = "Example";
private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME = "io.swagger.annotations.ApiModelProperty";
public CommentGenerator() {
properties = new Properties();
}
/**
* 设置用户配置的参数
*/
@Override
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
/**
* 给字段添加注释
*/
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加备注信息
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
// addFieldJavaDoc(field, remarks);
//数据库中特殊字符需要转义
if (remarks.contains("\"")) {
remarks = remarks.replace("\"", "'");
}
//数据库字段注释
// field.addJavaDocLine("/**");
// field.addJavaDocLine("*" + remarks + "");
// field.addJavaDocLine("*/");
//给model的字段添加swagger注解
if (addSwaggerUi) {
field.addJavaDocLine("@ApiModelProperty(value = \"" + remarks + "\")");
}
if (introspectedColumn.getJdbcTypeName().equals("TIMESTAMP")){
field.addJavaDocLine("@JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\",timezone = \"GMT+8\")");
}
}
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
if (addSwaggerUi) {
//只在model中添加swagger注解类的导入
if (!compilationUnit.isJavaInterface() && !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
if (addLombok) {
if (!compilationUnit.isJavaInterface() && !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {
compilationUnit.addImportedType(new FullyQualifiedJavaType(LOMBOK_DATA));
compilationUnit.addImportedType(new FullyQualifiedJavaType(ACCESSORS));
compilationUnit.addImportedType(new FullyQualifiedJavaType(JSON_FORMAT));
}
}
}
/**
* 在生成的model上添加注释
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
//addRemarkComments为true则执行
if (!addAuthorAndDate) {
return;
}
String author = properties.getProperty("author");
String dateFormat = properties.getProperty("dateFormat", "yyyy-MM-dd");
SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
// 获取表注释
String remarks = introspectedTable.getRemarks();
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * " + remarks);
topLevelClass.addJavaDocLine(" *");
topLevelClass.addJavaDocLine(" * @author " + author);
topLevelClass.addJavaDocLine(" * @date " + dateFormatter.format(new Date()));
topLevelClass.addJavaDocLine(" */");
if (addLombok) {
topLevelClass.addJavaDocLine("@Data");
topLevelClass.addJavaDocLine("@Accessors(chain = true)");
}
}
}
Generator
public class Generator {
public static void main(String[] args) throws Exception {
//MBG 执行过程中的警告信息
List<String> warnings = new ArrayList<String>();
//当生成的代码重复时,覆盖原代码
boolean overwrite = true;
//读取我们的 MBG 配置文件
InputStream is = Generator.class.getResourceAsStream("/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
//创建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//执行生成代码
myBatisGenerator.generate(null);
//输出警告信息
for (String warning : warnings) {
System.out.println(warning);
}
}
}

LombokPlugin
public class LombokPlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
}
@Override
public boolean modelSetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
//不生成getter
return false;
}
@Override
public boolean modelGetterMethodGenerated(Method method, TopLevelClass topLevelClass, IntrospectedColumn introspectedColumn, IntrospectedTable introspectedTable, ModelClassType modelClassType) {
//不生成setter
return false;
}
}
目录
网友评论