新建專案也行,在原專案里添加代碼也可。
先配置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="https://bbs.csdn.net/topics/true"/>
<!-- 是否去除所有自動生成的注釋 true:是 : false:否 -->
<property name="suppressAllComments" value="https://bbs.csdn.net/topics/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="https://bbs.csdn.net/topics/false"/>
<property name="trimStrings" value="https://bbs.csdn.net/topics/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="https://bbs.csdn.net/topics/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="https://bbs.csdn.net/topics/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檔案的位置,根據代碼必須要放在如圖位置才能被訪問到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/12786.html
標籤:非技術區
