IDEA下配置Mybatis的逆向工程

weixin_48420450 2020-09-05 01:55:48
新建项目也行,在原项目里添加代码也可。
先配置pom文件

<!-- mysql数据库驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>


配置 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="DB2Tables" targetRuntime="MyBatis3">
<!-- 生成mysql带有分页的sql的插件 这个可以自己写,-->
<plugin type="generator.MysqlPaginationPlugin" />
<plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
<plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
<!-- 自定义的注释规则,继承 DefaultCommentGenerator 重写 一些方法 -->
<commentGenerator type="generator.NewbatisGenerator">
<!-- 是否去除自动生成日期的注释 true:是 : false:否 -->
<property name="suppressDate" value="true"/>
<!-- 是否去除所有自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/school?charactorEncoding=utf-8"
userId="root"
password="root1234">
</jdbcConnection>
<!--生成entity类存放位置 targetPackage="包名(com.generator.test.entity)" targetProject="项目地址到\java (D:\workspace\src\main\java)"-->
<javaModelGenerator targetPackage="com.feng.ssm.po" targetProject=".\src">
<!-- enableSubPackages是否让schema作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件存放位置 targetPackage="包名(com.generator.test.mapper)" targetProject="项目地址到\java (D:\workspace\src\main\java)"-->
<sqlMapGenerator targetPackage="com.feng.ssm.mapper" targetProject=".\src">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!--生成Dao类存放位置 targetPackage="包名(com.generator.test.dao)"
targetProject="项目地址到\java (D:\workspace\src\main\java)"-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.feng.ssm.mapper"
targetProject=".\src">
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<table tableName="user" domainObjectName="User">
</table>
</context>
</generatorConfiguration>


对注解的改造

public class NewbatisGenerator extends DefaultCommentGenerator {
private Properties properties;
private Properties systemPro;
private boolean suppressDate;
private boolean suppressAllComments;
private String currentDateStr;

public NewbatisGenerator() {
super();
properties = new Properties();
systemPro = System.getProperties();
suppressDate = false;
suppressAllComments = false;
currentDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());
}

/**
* 对类的注解
* @param topLevelClass
* @param introspectedTable
*/
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
topLevelClass.addJavaDocLine("/**");
topLevelClass.addJavaDocLine(" * 这是MyBatis Generator自动生成的Model Class.");

StringBuilder sb = new StringBuilder();
sb.append(" * 对应的数据表是 : ");
sb.append(introspectedTable.getFullyQualifiedTable());
topLevelClass.addJavaDocLine(sb.toString());

String tableRemarks = introspectedTable.getRemarks();
if (!StringUtils.isEmpty(tableRemarks)) {
sb.setLength(0);
sb.append(" * 数据表注释 : ");
sb.append(tableRemarks);
topLevelClass.addJavaDocLine(sb.toString());
}

sb.setLength(0);
sb.append(" * @author ");
sb.append(systemPro.getProperty("user.name"));
topLevelClass.addJavaDocLine(sb.toString());

String curDateString = (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(new Date());
sb.setLength(0);
sb.append(" * @date ");
sb.append(curDateString);
topLevelClass.addJavaDocLine(sb.toString());

topLevelClass.addJavaDocLine(" */");
}

/**
* 生成的实体增加字段的中文注释
*/
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if (suppressAllComments) {
return;
}
StringBuilder sb = new StringBuilder();
field.addJavaDocLine("/**");
sb.append(" * ");
sb.append(introspectedColumn.getRemarks());
field.addJavaDocLine(sb.toString().replace("\n", " "));
field.addJavaDocLine(" */");
}

}


对分页的改造

public class MysqlPaginationPlugin extends PluginAdapter {
public MysqlPaginationPlugin() {}

public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
IntrospectedTable introspectedTable) {
this.addLimit(topLevelClass, introspectedTable, "limitStart");
this.addLimit(topLevelClass, introspectedTable, "limitSize");
return super.modelExampleClassGenerated(topLevelClass, introspectedTable);
}

public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(XmlElement element,
IntrospectedTable introspectedTable) {
XmlElement isNotNullElement = new XmlElement("if");
isNotNullElement
.addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0"));
isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}"));
element.addElement(isNotNullElement);
return super.sqlMapSelectByExampleWithoutBLOBsElementGenerated(element, introspectedTable);
}

public boolean sqlMapSelectByExampleWithBLOBsElementGenerated(XmlElement element,
IntrospectedTable introspectedTable) {
XmlElement isNotNullElement = new XmlElement("if");
isNotNullElement
.addAttribute(new Attribute("test", "limitStart != null and limitSize >= 0"));
isNotNullElement.addElement(new TextElement("limit #{limitStart} , #{limitSize}"));
element.addElement(isNotNullElement);
return super.sqlMapSelectByExampleWithBLOBsElementGenerated(element, introspectedTable);
}

private void addLimit(TopLevelClass topLevelClass, IntrospectedTable introspectedTable,
String name) {
CommentGenerator commentGenerator = this.context.getCommentGenerator();
Field field = new Field(name, PrimitiveTypeWrapper.getIntegerInstance());
field.setVisibility(JavaVisibility.PROTECTED);
commentGenerator.addFieldComment(field, introspectedTable);
topLevelClass.addField(field);
char c = name.charAt(0);
String camel = Character.toUpperCase(c) + name.substring(1);
Method method = new Method("set" + camel);
method.setVisibility(JavaVisibility.PUBLIC);
method.addParameter(new Parameter(PrimitiveTypeWrapper.getIntegerInstance(), name));
StringBuilder sb = new StringBuilder();
sb.append("this.");
sb.append(name);
sb.append(" = ");
sb.append(name);
sb.append(";");
method.addBodyLine(sb.toString());
commentGenerator.addGeneralMethodComment(method, introspectedTable);
topLevelClass.addMethod(method);
Method getterMethod = AbstractJavaGenerator.getGetter(field);
commentGenerator.addGeneralMethodComment(getterMethod, introspectedTable);
topLevelClass.addMethod(getterMethod);
}

public boolean validate(List<String> warnings) {
return true;
}



/**
* 生成mapper.xml,文件内容会被清空再写入
* */
@Override
public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
sqlMap.setMergeable(false);
return super.sqlMapGenerated(sqlMap, introspectedTable);
}

}


最后一步:
public class Generator {

public static void main(String[] args) throws Exception{
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.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);

}
}


有一点要注意的是generatorConfig.xml,也是我要写这个帖子的原因,就是这个xml文件的位置,根据代码必须要放在如图位置才能被访问到。
...全文
13 点赞 收藏 回复
写回复
回复
切换为时间正序
请发表友善的回复…
发表回复
相关推荐
发帖
非技术区
创建于2007-09-28

2.3w+

社区成员

Java 非技术区
申请成为版主
帖子事件
创建了帖子
2020-09-05 01:55
社区公告
暂无公告