下載mysql驅(qū)動(dòng)和mybatis-generator相關(guān)包
需要下載mysql驅(qū)動(dòng)和mybatis-generator-core包呼巷×湔保可以使用gradle或maven等插件下載或直接去官網(wǎng)下載。本文以gradle為例召庞。
在build.gradle中添加依賴
/*mysql驅(qū)動(dòng)*/
compile 'mysql:mysql-connector-java:5.1.34'
/*mybatis 自動(dòng)生成插件*/
compile 'org.mybatis.generator:mybatis-generator-core:1.3.5'
在項(xiàng)目中增加配置文件:generatorConfig.xml
反向生成java文件岛心,需要一個(gè)配置文件来破,配置數(shù)據(jù)庫(kù)的連接,生成代碼的位置等信息忘古。
<?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">
<!-- 定義如何連接目標(biāo)數(shù)據(jù)庫(kù) -->
<jdbcConnection driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}"
userId="${jdbc.username}" password="${jdbc.password}">
</jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 指定生成 Java 模型對(duì)象所屬的包 -->
<javaModelGenerator targetPackage="com.ai.emall.bean.gbean" targetProject="src\main\generate">
<property name="enableSubPackages" value="false" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- 指定生成 SQL 映射文件所屬的包和的目標(biāo)項(xiàng)目 -->
<sqlMapGenerator targetPackage="mybatis.gmapper" targetProject="src\main\resources">
<property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- 指定目標(biāo)包和目標(biāo)項(xiàng)目生成的客戶端接口和類 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.ai.emall.dao.gdao" targetProject="src\main\generate">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 設(shè)置要生成的表名 -->
<table tableName="product" >
</table>
</context>
</generatorConfiguration>
創(chuàng)建Main方法徘禁,生成相關(guān)代碼
/**
* 生成mybaits相關(guān)mapper,bean,dao等
* @author ZWG
*
*/
public class MybatisGenerateRun {
public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
//加載generatorEmallConfig文件
File configFile = new File(MybatisGenerateRun.class.getClassLoader().getResource("generatorConfig.xml").getPath());
//加載數(shù)據(jù)庫(kù)信息,例如driverClassName髓堪,username,password,url等
Properties extraProperties = PropertiesLoaderUtils.loadAllProperties("mybatis/mybatis-emall.properties");
ConfigurationParser cp = new ConfigurationParser(extraProperties, warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
if(!CollectionUtils.isEmpty(warnings)){
for (String warn : warnings) {
System.out.println(warn);
}
}
System.out.println("生成成功送朱!");
}
}
運(yùn)行main方法,生成成功
自定義生成的注釋
通過上面生成的bean文件干旁,每個(gè)字段會(huì)生成相應(yīng)的注釋驶沼,生成的注釋如下:
public class Product {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column product.PRODUCT_ID
*
* @mbg.generated Tue Jan 10 19:45:10 CST 2017
*/
private Long productId;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column product.PRODUCT_ID
*
* @return the value of product.PRODUCT_ID
*
* @mbg.generated Tue Jan 10 19:45:10 CST 2017
*/
public Long getProductId() {
return productId;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column product.PRODUCT_ID
*
* @param productId the value for product.PRODUCT_ID
*
* @mbg.generated Tue Jan 10 19:45:10 CST 2017
*/
public void setProductId(Long productId) {
this.productId = productId;
}
}
可以看到這并不是我們想要的注釋,如果我們想生成數(shù)據(jù)庫(kù)中的注釋争群,可以使用Mybatis提供的CommentGenerator接口回怜,具體步驟如下:
1. 創(chuàng)建自定義注釋生成類,需要繼承CommentGenerator接口
/**
* 自定義Mybatis注釋 使用數(shù)據(jù)庫(kù)中的注釋
* @author ZWG
*
*/
public class MybatisGeneratorCommon implements CommentGenerator{
@Override
public void addConfigurationProperties(Properties properties) {}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
//判斷數(shù)據(jù)庫(kù)中該字段注釋是否為空
if(StringUtils.isEmpty(introspectedColumn.getRemarks()))
return;
field.addJavaDocLine("/**"+introspectedColumn.getRemarks()+"*/");
}
@Override
public void addFieldComment(Field field, IntrospectedTable introspectedTable) {}
@Override
public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {}
@Override
public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {}
@Override
public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {}
@Override
public void addGetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if(StringUtils.isEmpty(introspectedColumn.getRemarks()))
return;
method.addJavaDocLine("/**獲取"+introspectedColumn.getRemarks()+"*/");
}
@Override
public void addSetterComment(Method method, IntrospectedTable introspectedTable,
IntrospectedColumn introspectedColumn) {
if(StringUtils.isEmpty(introspectedColumn.getRemarks()))
return;
method.addJavaDocLine("/**設(shè)置"+introspectedColumn.getRemarks()+"*/");
}
@Override
public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {}
@Override
public void addJavaFileComment(CompilationUnit compilationUnit) {}
@Override
public void addComment(XmlElement xmlElement) {}
@Override
public void addRootComment(XmlElement rootElement) {}
}
1. 將自定義的注釋類添加到配置中祭阀。
在上面generatorConfig.xml中的context元素中增加如下信息:
<!-- 自定義注釋生成器 MybatisGeneratorCommon類為我自定義的繼承CommentGenerator的類 -->
<commentGenerator type="com.ai.emall.util.MybatisGeneratorCommon">
<!-- 關(guān)閉自動(dòng)生成的注釋 -->
<property name="suppressAllComments" value="true" />
<property name="suppressDate" value="true" />
</commentGenerator>
注意:generatorConfig.xml中的context下面的元素有嚴(yán)格的順序關(guān)系鹉戚,上面的commentGenerator需要放到j(luò)dbcConnection標(biāo)簽的前面。==
具體順序?yàn)椋?(property,plugin,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeResolver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table +)".
使用自定義注釋類专控,生成的bean文件如下:
public class Product {
/**產(chǎn)品ID*/
private Long productId;
/**獲取產(chǎn)品ID*/
public Long getProductId() {
return productId;
}
/**設(shè)置產(chǎn)品ID*/
public void setProductId(Long productId) {
this.productId = productId;
}
}
參考:
generatorConfig.xml完整的配置文件
mybatis-generator 官網(wǎng)
mybatis-generator用戶指南