搭建新版的mybatis dynamic不想写xml的,在这里看齐.
首先引入maven的配置文件
<mysql.version>8.0.11</mysql.version>
<mybatis.version>1.3.2</mybatis.version>
<mybatis-generator.version>1.3.7</mybatis-generator.version>
<mybatis-dynamic-sql.version>1.1.4</mybatis-dynamic-sql.version>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis动态sql-->
<dependency>
<groupId>org.mybatis.dynamic-sql</groupId>
<artifactId>mybatis-dynamic-sql</artifactId>
<version>${mybatis-dynamic-sql.version}</version>
</dependency>
<!-- MyBatis 生成器 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>${mybatis-generator.version}</version>
<optional>true</optional>
</dependency>
再来生成mapper文件的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>
<!--Mybatis Generator目前有5种运行模式,分别为:MyBatis3DynamicSql、MyBatis3Kotlin、MyBatis3、MyBatis3Simple、MyBatis3DynamicSqlV1。-->
<context id="springboot-base" targetRuntime="MyBatis3DynamicSql">
<commentGenerator type="com.data.flag.test.CommentGenerator">
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
<property name="addRemarkComments" value="true"/>
</commentGenerator>
<jdbcConnection connectionURL="jdbc:mysql://127.0.0.1:3306/test?tinyInt1isBit=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true"
driverClass="com.mysql.jdbc.Driver" password="123456" userId="root" />
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer, 为 true时把JDBC DECIMAL
和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver type="com.code.flag.gen.MyJavaTypeResolverImpl"/>
<!-- targetProject:生成PO类的位置 -->
<javaModelGenerator targetPackage="com.data.flag.entity" targetProject="src/main/java">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 -->
<sqlMapGenerator targetPackage="mybatis.mapping" targetProject="src/main/resources">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator targetPackage="com.data.flag.mapper" targetProject="src/main/java" type="XMLMAPPER">
<!-- enableSubPackages:是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!--生成全部表tableName设为%-->
<table tableName="test_connection" />
</context>
</generatorConfiguration>
再来个自定义注释生成器
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import java.util.Properties;
import java.util.Set;
/**
* 自定义注释生成器
*
* @author chengge
* @version 1.0
* @since 2021/1/28
*/
public class CommentGenerator extends DefaultCommentGenerator {
private boolean addRemarkComments = false;
private static final String EXAMPLE_SUFFIX = "Example";
private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME = "io.swagger.annotations.ApiModelProperty";
/**
* 设置用户配置的参数
*/
@Override
public void addConfigurationProperties(Properties properties) {
super.addConfigurationProperties(properties);
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
}
@Override
public void addFieldAnnotation(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn, Set<FullyQualifiedJavaType> imports) {
if (field.getInitializationString() == null) {
String remarks = introspectedColumn.getRemarks();
//根据参数和备注信息判断是否添加备注信息
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
//数据库中特殊字符需要转义
if (remarks.contains("\"")) {
remarks = remarks.replace("\"", "'");
}
//给model的字段添加swagger注解
field.addJavaDocLine("@ApiModelProperty(value = \"" + remarks + "\")");
}
}
super.addFieldAnnotation(field, introspectedTable, introspectedColumn, imports);
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
super.addJavaFileComment(compilationUnit);
//只在model中添加swagger注解类的导入
if (!compilationUnit.isJavaInterface() && !compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)) {
compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
}
}
}
嗯,还有一个自定义字段类型
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.JavaTypeResolver;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.config.Context;
import org.mybatis.generator.internal.util.StringUtility;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* 自定义字段类型
* @author chengge
* @since 2021/1/28
*/
@Service
public class MyJavaTypeResolverImpl implements JavaTypeResolver {
protected List<String> warnings;
protected Properties properties = new Properties();
protected Context context;
protected boolean forceBigDecimals;
protected Map<Integer, JdbcTypeInformation> typeMap = new HashMap();
public MyJavaTypeResolverImpl() {
this.typeMap.put(2003, new MyJavaTypeResolverImpl.JdbcTypeInformation("ARRAY", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(-5, new MyJavaTypeResolverImpl.JdbcTypeInformation("BIGINT", new FullyQualifiedJavaType(BigDecimal.class.getName())));
this.typeMap.put(-2, new MyJavaTypeResolverImpl.JdbcTypeInformation("BINARY", new FullyQualifiedJavaType("byte[]")));
this.typeMap.put(-7, new MyJavaTypeResolverImpl.JdbcTypeInformation("BIT", new FullyQualifiedJavaType(Boolean.class.getName())));
this.typeMap.put(2004, new MyJavaTypeResolverImpl.JdbcTypeInformation("BLOB", new FullyQualifiedJavaType("byte[]")));
this.typeMap.put(16, new MyJavaTypeResolverImpl.JdbcTypeInformation("BOOLEAN", new FullyQualifiedJavaType(Boolean.class.getName())));
this.typeMap.put(1, new MyJavaTypeResolverImpl.JdbcTypeInformation("CHAR", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(2005, new MyJavaTypeResolverImpl.JdbcTypeInformation("CLOB", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(70, new MyJavaTypeResolverImpl.JdbcTypeInformation("DATALINK", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(91, new MyJavaTypeResolverImpl.JdbcTypeInformation("DATE", new FullyQualifiedJavaType(LocalDateTime.class.getName())));
this.typeMap.put(3, new MyJavaTypeResolverImpl.JdbcTypeInformation("DECIMAL", new FullyQualifiedJavaType(Double.class.getName())));
this.typeMap.put(2001, new MyJavaTypeResolverImpl.JdbcTypeInformation("DISTINCT", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(8, new MyJavaTypeResolverImpl.JdbcTypeInformation("DOUBLE", new FullyQualifiedJavaType(Double.class.getName())));
this.typeMap.put(6, new MyJavaTypeResolverImpl.JdbcTypeInformation("FLOAT", new FullyQualifiedJavaType(Double.class.getName())));
this.typeMap.put(4, new MyJavaTypeResolverImpl.JdbcTypeInformation("INTEGER", new FullyQualifiedJavaType(Integer.class.getName())));
this.typeMap.put(2000, new MyJavaTypeResolverImpl.JdbcTypeInformation("JAVA_OBJECT", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(-16, new MyJavaTypeResolverImpl.JdbcTypeInformation("LONGNVARCHAR", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(-4, new MyJavaTypeResolverImpl.JdbcTypeInformation("LONGVARBINARY", new FullyQualifiedJavaType("byte[]")));
this.typeMap.put(-1, new MyJavaTypeResolverImpl.JdbcTypeInformation("LONGVARCHAR", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(-15, new MyJavaTypeResolverImpl.JdbcTypeInformation("NCHAR", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(2011, new MyJavaTypeResolverImpl.JdbcTypeInformation("NCLOB", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(-9, new MyJavaTypeResolverImpl.JdbcTypeInformation("NVARCHAR", new FullyQualifiedJavaType(String.class.getName())));
this.typeMap.put(0, new MyJavaTypeResolverImpl.JdbcTypeInformation("NULL", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(2, new MyJavaTypeResolverImpl.JdbcTypeInformation("NUMERIC", new FullyQualifiedJavaType(BigDecimal.class.getName())));
this.typeMap.put(1111, new MyJavaTypeResolverImpl.JdbcTypeInformation("OTHER", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(7, new MyJavaTypeResolverImpl.JdbcTypeInformation("REAL", new FullyQualifiedJavaType(Float.class.getName())));
this.typeMap.put(2006, new MyJavaTypeResolverImpl.JdbcTypeInformation("REF", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(5, new MyJavaTypeResolverImpl.JdbcTypeInformation("SMALLINT", new FullyQualifiedJavaType(Short.class.getName())));
this.typeMap.put(2002, new MyJavaTypeResolverImpl.JdbcTypeInformation("STRUCT", new FullyQualifiedJavaType(Object.class.getName())));
this.typeMap.put(92, new MyJavaTypeResolverImpl.JdbcTypeInformation("TIME", new FullyQualifiedJavaType(LocalDateTime.class.getName())));
this.typeMap.put(93, new MyJavaTypeResolverImpl.JdbcTypeInformation("TIMESTAMP", new FullyQualifiedJavaType(LocalDateTime.class.getName())));
this.typeMap.put(-6, new MyJavaTypeResolverImpl.JdbcTypeInformation("TINYINT", new FullyQualifiedJavaType(Integer.class.getName())));
this.typeMap.put(-3, new MyJavaTypeResolverImpl.JdbcTypeInformation("VARBINARY", new FullyQualifiedJavaType("byte[]")));
this.typeMap.put(12, new MyJavaTypeResolverImpl.JdbcTypeInformation("VARCHAR", new FullyQualifiedJavaType(String.class.getName())));
}
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
this.forceBigDecimals = StringUtility.isTrue(properties.getProperty("forceBigDecimals"));
}
@Override
public void setContext(Context context) {
this.context = context;
}
public FullyQualifiedJavaType calculateJavaType(IntrospectedColumn introspectedColumn) {
FullyQualifiedJavaType answer = null;
MyJavaTypeResolverImpl.JdbcTypeInformation jdbcTypeInformation = (MyJavaTypeResolverImpl.JdbcTypeInformation)this.typeMap.get(introspectedColumn.getJdbcType());
if (jdbcTypeInformation != null) {
answer = jdbcTypeInformation.getFullyQualifiedJavaType();
answer = this.overrideDefaultType(introspectedColumn, answer);
}
return answer;
}
protected FullyQualifiedJavaType overrideDefaultType(IntrospectedColumn column, FullyQualifiedJavaType defaultType) {
FullyQualifiedJavaType answer = defaultType;
switch(column.getJdbcType()) {
case -7:
answer = this.calculateBitReplacement(column, defaultType);
break;
case 2:
case 3:
answer = this.calculateBigDecimalReplacement(column, defaultType);
}
return answer;
}
protected FullyQualifiedJavaType calculateBitReplacement(IntrospectedColumn column, FullyQualifiedJavaType defaultType) {
FullyQualifiedJavaType answer;
if (column.getLength() > 1) {
answer = new FullyQualifiedJavaType("byte[]");
} else {
answer = defaultType;
}
return answer;
}
protected FullyQualifiedJavaType calculateBigDecimalReplacement(IntrospectedColumn column, FullyQualifiedJavaType defaultType) {
FullyQualifiedJavaType answer;
if (column.getScale() <= 0 && column.getLength() <= 18 && !this.forceBigDecimals) {
if (column.getLength() > 9) {
answer = new FullyQualifiedJavaType(Double.class.getName());
} else if (column.getLength() > 4) {
answer = new FullyQualifiedJavaType(Integer.class.getName());
} else {
answer = new FullyQualifiedJavaType(Short.class.getName());
}
} else {
answer = defaultType;
}
return answer;
}
public String calculateJdbcTypeName(IntrospectedColumn introspectedColumn) {
String answer = null;
MyJavaTypeResolverImpl.JdbcTypeInformation jdbcTypeInformation = (MyJavaTypeResolverImpl.JdbcTypeInformation)this.typeMap.get(introspectedColumn.getJdbcType());
if (jdbcTypeInformation != null) {
answer = jdbcTypeInformation.getJdbcTypeName();
}
return answer;
}
public void setWarnings(List<String> warnings) {
this.warnings = warnings;
}
public static class JdbcTypeInformation {
private String jdbcTypeName;
private FullyQualifiedJavaType fullyQualifiedJavaType;
public JdbcTypeInformation(String jdbcTypeName, FullyQualifiedJavaType fullyQualifiedJavaType) {
this.jdbcTypeName = jdbcTypeName;
this.fullyQualifiedJavaType = fullyQualifiedJavaType;
}
public String getJdbcTypeName() {
return this.jdbcTypeName;
}
public FullyQualifiedJavaType getFullyQualifiedJavaType() {
return this.fullyQualifiedJavaType;
}
}
}
最后来个生成表的main方法
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* 持久层代码生成器
*
* @author chengge
* @version 1.0
* @since 2021/1/28
*/
@Slf4j
public class Generator {
@SneakyThrows
public static void main(String[] args) {
//MBG 执行过程中的警告信息
List<String> warnings = new ArrayList<>();
//读取我们的 MBG 配置文件
InputStream is = Generator.class.getResourceAsStream("/mybatis/generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
//当生成的代码重复时,不要覆盖原代码
DefaultShellCallback callback = new DefaultShellCallback(true);
//创建 MBG
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
//执行生成代码
myBatisGenerator.generate(null);
//输出警告信息
for (String warning : warnings) {
log.info(warning);
}
}
}
再来官方使用的mybatis dynamic, Api地址:https://mybatis.org/mybatis-dynamic-sql/docs/introduction.html
感谢各位小伙伴,支持我,请收藏点赞哦。