Mybatis 代码生成器使用(生成某张表的相关代码)
- 其实MyBatis Generator就可以实现所有的功能,为了学习一下随便写的
引入依赖
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.39</version>
</dependency>
</dependencies>
生成器主类
public class Generator {
private static Logger logger = Logger.getLogger(String.valueOf(Generator.class));
public static void main(String[] args) {
logger.info("=====>准备生成代码");
String table = null;
String file = null;
try {
System.out.println("请输入表名:");
InputStream in = System.in;
Scanner scanner = new Scanner(in);
table = scanner.next();
logger.info("=====>表名称为:"+table);
System.out.println("请输入数据库配置文件名:");
file = scanner.next();
logger.info("=====>文件位置为:"+file);
scanner.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
String test="D:\\TrainingCode\\JavaTraining\\mybatis-generator\\src\\main\\resources\\generator\\generatorConfig.xml";
String test1 = "security_algorithm";
List<String> warnings = new ArrayList<>();
boolean overwrite = true;
logger.info("=====>读到数据库配置文件位置");
File configFile = new File(file);
if(!configFile.exists()){
logger.info("=====>文件不存在!");
return;
}
ConfigurationParser cp = new ConfigurationParser(warnings);
try {
Configuration config = cp.parseConfiguration(configFile);
if(Objects.nonNull(table) && table.length()>0) {
List<Context> contexts = config.getContexts();
Context context = contexts.get(0);
List<TableConfiguration> tableConfigurations = context.getTableConfigurations();
TableConfiguration tableConfiguration = tableConfigurations.get(0);
tableConfiguration.setTableName(table);
context.addTableConfiguration(tableConfiguration);
}
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
logger.info("生成代码完成!");
} catch (Exception e) {
logger.info("=====>代码生成出错:"+e.getMessage());
}
}
}
生成代码注释配置类
public class MyCommentGenerator implements CommentGenerator {
private Properties properties = new Properties();
private boolean suppressDate = false;
private boolean suppressAllComments = false;
private boolean addRemarkComments = false;
private SimpleDateFormat dateFormat;
public MyCommentGenerator() {
super();
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
}
@Override
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
this.suppressDate = StringUtility.isTrue(properties.getProperty("suppressDate"));
this.suppressAllComments = StringUtility.isTrue(properties.getProperty("suppressAllComments"));
this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
String dateFormatString = properties.getProperty("dateFormat");
if (StringUtility.stringHasValue(dateFormatString)) {
this.dateFormat = new SimpleDateFormat(dateFormatString);
}
}
protected String getDateString() {
if (this.suppressDate) {
return null;
} else {
return this.dateFormat != null ? this.dateFormat.format(new Date()) : (new Date()).toString();
}
}
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
if (!this.suppressAllComments) {
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * @author LiDong");
topLevelClass.addJavaDocLine(" * @version 1.0.0 ");
topLevelClass.addJavaDocLine(" * @description MyBatis Generator 自动创建,对应数据表为:" + introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(" * @createTime " + this.getDateString());
topLevelClass.addJavaDocLine(" */");
}
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {
}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean b) {
}
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
if (!this.suppressAllComments) {
field.addJavaDocLine("/**");
String remarks = introspectedColumn.getRemarks();
if (Objects.nonNull(remarks) && remarks.length()>0) {
// 通过换行符分割 System.getProperty("line.separator"):换行符 ,屏蔽了 Windows和Linux的区别
String[] remarkLines = remarks.split(System.getProperty("line.separator"));
int length = remarkLines.length;
// 如果有多行,就换行显示
for (int i = 0; i < length; i++) {
String remarkLine = remarkLines[i];
field.addJavaDocLine(" * " + remarkLine);
}
}else {
field.addJavaDocLine(" * "+field.getName());
}
// 注释结束
field.addJavaDocLine(" */");
}
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
}
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {
if (!this.suppressAllComments) {
method.addJavaDocLine("/**");
method.addJavaDocLine(" * " + method.getName());
List<Parameter> parameters = method.getParameters();
parameters.forEach(parameter -> method.addJavaDocLine(" * @param " + parameter.getName()));
String returnType = "void";
if (!returnType.equals(method.getReturnType())) {
method.addJavaDocLine(" * @return ");
}
method.addJavaDocLine(" */");
}
}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {
}
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable, IntrospectedColumn introspectedColumn) {
}
@Override
public void addComment(XmlElement xmlElement) {
}
@Override
public void addRootComment(XmlElement xmlElement) {
}
}
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>
<context id="MySQLTables" targetRuntime="MyBatis3">
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<commentGenerator type="mybatisgenerate.MyCommentGenerator"></commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/shop?useUnicode=yes&characterEncoding=UTF-8&useSSL=false"
userId="root"
password="0000">
</jdbcConnection>
<javaModelGenerator targetPackage="com.li.domain" targetProject=".">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.li.mapper" targetProject=".">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.li.mapper" targetProject=".">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<table schema="shop" tableName="" ></table>
</context>
</generatorConfiguration>
使用
- 打jar包,java -jar 启动 输入相应的参数
-![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6e920116426a0b0965cd13108a873e4a.png)