MyBatis Generator使用com.mysql.cj.jdbc.Driver
Mybatis Generator 1.3.5
新建了一个decision库,并创建了一张user表
import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.internal.DefaultShellCallback;
import com.google.common.base.CaseFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.tydt.decision.core.ProjectConstant.*; public class CodeGenerator {
//JDBC配置,请修改为你项目的实际配置
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/decision?serverTimezone=GMT%2B8&characterEncoding=utf8";
private static final String JDBC_USERNAME = "root";
private static final String JDBC_PASSWORD = "root";
private static final String JDBC_DIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver"; private static final String PROJECT_PATH = System.getProperty("user.dir");//项目在硬盘上的基础路径
private static final String TEMPLATE_FILE_PATH = PROJECT_PATH + "/src/test/resources/generator/template";//模板位置 private static final String JAVA_PATH = "/src/main/java"; //java文件路径
private static final String RESOURCES_PATH = "/src/main/resources";//资源文件路径 private static final String PACKAGE_PATH_SERVICE = packageConvertPath(SERVICE_PACKAGE);//生成的Service存放路径
private static final String PACKAGE_PATH_SERVICE_IMPL = packageConvertPath(SERVICE_IMPL_PACKAGE);//生成的Service实现存放路径
private static final String PACKAGE_PATH_CONTROLLER = packageConvertPath(CONTROLLER_PACKAGE);//生成的Controller存放路径 private static final String AUTHOR = "Beibei";//@author
private static final String DATE = new SimpleDateFormat("yyyy/MM/dd").format(new Date());//@date public static void main(String[] args) {
genCode("user");
//genCodeByCustomModelName("输入表名","输入自定义Model名称");
} /**
* 通过数据表名称生成代码,Model 名称通过解析数据表名称获得,下划线转大驼峰的形式。
* 如输入表名称 "t_user_detail" 将生成 TUserDetail、TUserDetailMapper、TUserDetailService ...
* @param tableNames 数据表名称...
*/
public static void genCode(String... tableNames) {
for (String tableName : tableNames) {
genCodeByCustomModelName(tableName, null);
}
} /**
* 通过数据表名称,和自定义的 Model 名称生成代码
* 如输入表名称 "t_user_detail" 和自定义的 Model 名称 "User" 将生成 User、UserMapper、UserService ...
* @param tableName 数据表名称
* @param modelName 自定义的 Model 名称
*/
public static void genCodeByCustomModelName(String tableName, String modelName) {
genModelAndMapper(tableName, modelName);
} public static void genModelAndMapper(String tableName, String modelName) {
Context context = new Context(ModelType.FLAT);
context.setId("Potato");
context.setTargetRuntime("MyBatis3Simple");
context.addProperty(PropertyRegistry.CONTEXT_BEGINNING_DELIMITER, "`");
context.addProperty(PropertyRegistry.CONTEXT_ENDING_DELIMITER, "`"); JDBCConnectionConfiguration jdbcConnectionConfiguration = new JDBCConnectionConfiguration();
jdbcConnectionConfiguration.setConnectionURL(JDBC_URL);
jdbcConnectionConfiguration.setUserId(JDBC_USERNAME);
jdbcConnectionConfiguration.setPassword(JDBC_PASSWORD);
jdbcConnectionConfiguration.setDriverClass(JDBC_DIVER_CLASS_NAME);
context.setJdbcConnectionConfiguration(jdbcConnectionConfiguration); PluginConfiguration pluginConfiguration = new PluginConfiguration();
pluginConfiguration.setConfigurationType("tk.mybatis.mapper.generator.MapperPlugin");
pluginConfiguration.addProperty("mappers", MAPPER_INTERFACE_REFERENCE);
context.addPluginConfiguration(pluginConfiguration); JavaModelGeneratorConfiguration javaModelGeneratorConfiguration = new JavaModelGeneratorConfiguration();
javaModelGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
javaModelGeneratorConfiguration.setTargetPackage(MODEL_PACKAGE);
context.setJavaModelGeneratorConfiguration(javaModelGeneratorConfiguration); SqlMapGeneratorConfiguration sqlMapGeneratorConfiguration = new SqlMapGeneratorConfiguration();
sqlMapGeneratorConfiguration.setTargetProject(PROJECT_PATH + RESOURCES_PATH);
sqlMapGeneratorConfiguration.setTargetPackage("mapper");
context.setSqlMapGeneratorConfiguration(sqlMapGeneratorConfiguration); JavaClientGeneratorConfiguration javaClientGeneratorConfiguration = new JavaClientGeneratorConfiguration();
javaClientGeneratorConfiguration.setTargetProject(PROJECT_PATH + JAVA_PATH);
javaClientGeneratorConfiguration.setTargetPackage(MAPPER_PACKAGE);
javaClientGeneratorConfiguration.setConfigurationType("XMLMAPPER");
context.setJavaClientGeneratorConfiguration(javaClientGeneratorConfiguration); TableConfiguration tableConfiguration = new TableConfiguration(context);
tableConfiguration.setTableName(tableName);
if (StringUtils.isNotEmpty(modelName))tableConfiguration.setDomainObjectName(modelName);
tableConfiguration.setGeneratedKey(new GeneratedKey("id", "Mysql", true, null));
context.addTableConfiguration(tableConfiguration); List<String> warnings;
MyBatisGenerator generator;
try {
Configuration config = new Configuration();
config.addContext(context);
config.validate(); boolean overwrite = true;
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
warnings = new ArrayList<String>();
generator = new MyBatisGenerator(config, callback, warnings);
generator.generate(null);
} catch (Exception e) {
throw new RuntimeException("生成Model和Mapper失败", e);
} if (generator.getGeneratedJavaFiles().isEmpty() || generator.getGeneratedXmlFiles().isEmpty()) {
throw new RuntimeException("生成Model和Mapper失败:" + warnings);
}
if (StringUtils.isEmpty(modelName)) modelName = tableNameConvertUpperCamel(tableName);
System.out.println(modelName + ".java 生成成功");
System.out.println(modelName + "Mapper.java 生成成功");
System.out.println(modelName + "Mapper.xml 生成成功");
} private static String tableNameConvertUpperCamel(String tableName) {
return CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName.toLowerCase()); } private static String packageConvertPath(String packageName) {
return String.format("/%s/", packageName.contains(".") ? packageName.replaceAll("\\.", "/") : packageName);
}
}
直接运行后输出
User.java 生成成功
UserMapper.java 生成成功
UserMapper.xml 生成成功
但是打开User.java,发现字段包括本地所有包换user表的字段
org.mybatis.generator.internal.db.DatabaseIntrospector
ResultSet rs = databaseMetaData.getColumns(localCatalog, localSchema,localTableName, "%");
localCatalog是null,在底层会执行SHOW DATABASES 得到所有的数据库
在连接中少配置了一个属性nullCatalogMeansCurrent=true
将连接配置的那句改为
JDBC_URL = "jdbc:mysql://localhost:3306/decision?serverTimezone=GMT%2B8&characterEncoding=utf8&nullCatalogMeansCurrent=true"
修改完后,重新运行,User.java里面的字段只是decision数据库里的user了,问题解决
nullCatalogMeansCurrent=true使用com.mysql.cj.jdbc.Driver
这个驱动的时候,要加上这个属性。
在项目中不需要加,但是在使用Mybatis Generator时要加上。