MyBatis逆向工厂
介绍:
就是使用简单的理解,MyBatis逆向工程,就是通过相应插件,自动生成MyBatis数据库连接的一些文件。mybatis需要编写sql语句,mybatis官方提供逆向工程,可以针对单表自动生成mybatis执行所需要的代码(mapper.java、mapper.xml、pojo…),提高工作效率。
使用操作
声明:此操作在mysql创建数据库后执行
1.在pom.xml中添加依赖
<!-- MBG mybatis逆向工程-->
<!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
2.创建java下目录
如下图所示:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-BHGqHcRx-1603599934903)(C:\Users\HP\AppData\Roaming\Typora\typora-user-images\1586921891889.png)]
以上三个必要的 resources中的文件皆是在ssm整合时创建(具体见文件ssm整合2)
3.在项目下创建一个mbg.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="DB2Tables" targetRuntime="MyBatis3">
<!-- 指定生成的java文件的编码,没有直接生成到项目时中文可能会乱码 -->
<property name="javaFileEncoding" value="UTF-8" />
<!--配置生成pojo的序列化的插件-->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!--配置生成pojo的toString()方法插件-->
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<!-- 取消生成的注释 -->
<!-- <commentGenerator>
<property name="suppressDate" value="false"/>
<property name="suppressAllComments" value="false"/>
</commentGenerator> -->
<!-- 通过type指定自定义的注释 -->
<commentGenerator type="com.example.comment.MyCommentGenerator">
<!-- 不要开启,否则将不会使用自定义注释 -->
<property name="suppressAllComments" value="false" />
</commentGenerator>
<!-- 配置数据库连接信息-->
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/wkfc?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--指定javaBean生成位置-->
<javaModelGenerator targetPackage="com.example.entity" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--指定sql映射文件生成的位置-->
<sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--指定dao接口生成的位置,mapper接口-->
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.example.mapper" targetProject=".\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--table指定每个表生成的生成策略-->
<table tableName="w_about" domainObjectName="About"></table>
<table tableName="w_admin" domainObjectName="Admin"></table>
<table tableName="w_com" domainObjectName="Com"></table>
</context>
</generatorConfiguration>
4.测试
创建一个测试类(我这类名为 mbgTest)
package com.example.test;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import java.io.File;W
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MbgTest {
public static void main(String[] args) {
try {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行即可看到:mapper bean 包下文件
但生成文件不太符合我们理想需求 进行修改;
5.自定义注释类
创建一个MyCommentGenerator类
package com.example.comment;
import static org.mybatis.generator.internal.util.StringUtility.isTrue;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Properties;
import org.mybatis.generator.api.CommentGenerator;
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.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;
import org.mybatis.generator.internal.util.StringUtility;
public class MyCommentGenerator implements CommentGenerator {
/** The properties. */
private Properties properties;
/** The suppress date. */
private boolean suppressDate;
/** The suppress all comments. */
private boolean suppressAllComments;
/** The addition of table remark's comments.
* If suppressAllComments is true, this option is ignored*/
private boolean addRemarkComments;
private SimpleDateFormat dateFormat;
public MyCommentGenerator() {
super();
properties = new Properties();
suppressDate = false;
suppressAllComments = false;
addRemarkComments = false;
}
public void addJavaFileComment(CompilationUnit compilationUnit) {
}
/**
* 实体类对应的mapper.xml注释,mapper类不加注释,如有需要参考 DefaultCommentGenerator
*/
public void addComment(XmlElement xmlElement) {
if (suppressAllComments) {
return;
}
}
public void addRootComment(XmlElement rootElement) {
}
public void addConfigurationProperties(Properties properties) {
this.properties.putAll(properties);
suppressDate = isTrue(properties
.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
suppressAllComments = isTrue(properties
.getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
addRemarkComments = isTrue(properties
.getProperty(PropertyRegistry.COMMENT_GENERATOR_ADD_REMARK_COMMENTS));
String dateFormatString = properties.getProperty(PropertyRegistry.COMMENT_GENERATOR_DATE_FORMAT);
if (StringUtility.stringHasValue(dateFormatString)) {
dateFormat = new SimpleDateFormat(dateFormatString);
}
}
protected void addJavadocTag(JavaElement javaElement,
boolean markAsDoNotDelete) {
javaElement.addJavaDocLine(" *"); //$NON-NLS-1$
StringBuilder sb = new StringBuilder();
sb.append(" * "); //$NON-NLS-1$
sb.append(MergeConstants.NEW_ELEMENT_TAG);
if (markAsDoNotDelete) {
sb.append(" do_not_delete_during_merge"); //$NON-NLS-1$
}
String s = getDateString();
if (s != null) {
sb.append(' ');
sb.append(s);
}
javaElement.addJavaDocLine(sb.toString());
}
protected String getDateString() {
if (suppressDate) {
return null;
} else if (dateFormat != null) {
return dateFormat.format(new Date());
} else {
return new Date().toString();
}
}
public void addClassComment(InnerClass innerClass,
IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**"); //$NON-NLS-1$
sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString());
addJavadocTag(innerClass, false);
innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
}
public void addModelClassComment(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
if (suppressAllComments || !addRemarkComments) {
return;
}
StringBuilder sb = new StringBuilder();
topLevelClass.addJavaDocLine("/**"); //$NON-NLS-1$
String remarks = introspectedTable.getRemarks();
if (addRemarkComments && StringUtility.stringHasValue(remarks)) {
topLevelClass.addJavaDocLine(" * Database Table Remarks:");
String[] remarkLines = remarks.split(System.getProperty("line.separator")); //$NON-NLS-1$
for (String remarkLine : remarkLines) {
topLevelClass.addJavaDocLine(" * " + remarkLine); //$NON-NLS-1$
}
}
topLevelClass.addJavaDocLine(" *"); //$NON-NLS-1$
topLevelClass
.addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$
sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(sb.toString());
addJavadocTag(topLevelClass, true);
topLevelClass.addJavaDocLine(" */"); //$NON-NLS-1$
}
public void addEnumComment(InnerEnum innerEnum,
IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerEnum.addJavaDocLine("/**"); //$NON-NLS-1$
innerEnum
.addJavaDocLine(" * This enum was generated by MyBatis Generator."); //$NON-NLS-1$
sb.append(" * This enum corresponds to the database table "); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
innerEnum.addJavaDocLine(sb.toString());
addJavadocTag(innerEnum, false);
innerEnum.addJavaDocLine(" */"); //$NON-NLS-1$
}
/**
* 实体类字段注释
*/
public void addFieldComment(Field field,
IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
field.addJavaDocLine("/**"); //$NON-NLS-1$
// 核心代码 introspectedColumn.getRemarks() 就是获取字段注释
StringBuilder sb = new StringBuilder();
sb.append(" * " + introspectedColumn.getRemarks());
sb.append("\n\t * tianxincode@163.com");
sb.append("\n\t * " + LocalDateTime.now());
field.addJavaDocLine(sb.toString());
field.addJavaDocLine(" */");
}
/**
* 实体类的静态字段
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * tianxincode@163.com");
sb.append("\n\t * " + LocalDateTime.now());
field.addJavaDocLine(sb.toString());
field.addJavaDocLine(" */");
}
/**
* 实体类toString方法
*/
public void addGeneralMethodComment(Method method,
IntrospectedTable introspectedTable) {
if (suppressAllComments) {
return;
}
/* StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**"); //$NON-NLS-1$
method.addJavaDocLine(" * toString."); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
method.addJavaDocLine(sb.toString());
addJavadocTag(method, false);*/
//method.addJavaDocLine(" */");
}
/**
* 实体类getter方法注释
*/
public void addGetterComment(Method method,
IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**"); //$NON-NLS-1$
sb.append(" * " + introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
method.addJavaDocLine(" */"); //$NON-NLS-1$
}
/**
* 实体类setter注释
*/
public void addSetterComment(Method method,
IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**"); //$NON-NLS-1$
sb.append(" * " + introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
method.addJavaDocLine(" */"); //$NON-NLS-1$
}
public void addClassComment(InnerClass innerClass,
IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**"); //$NON-NLS-1$
innerClass
.addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString());
addJavadocTag(innerClass, markAsDoNotDelete);
innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
}
}
/**
* 实体类setter注释
*/
public void addSetterComment(Method method,
IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
method.addJavaDocLine("/**"); //$NON-NLS-1$
sb.append(" * " + introspectedColumn.getRemarks());
method.addJavaDocLine(sb.toString());
method.addJavaDocLine(" */"); //$NON-NLS-1$
}
public void addClassComment(InnerClass innerClass,
IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
innerClass.addJavaDocLine("/**"); //$NON-NLS-1$
innerClass
.addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$
sb.append(introspectedTable.getFullyQualifiedTable());
innerClass.addJavaDocLine(sb.toString());
addJavadocTag(innerClass, markAsDoNotDelete);
innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
}
}