一、导包
mybatis-generator-core.jar
二、创建配置文件mybatis-generator.xml
mbg.xml编写方法见MyBatis Generator参考文档:http://www.mybatis.org/generator/configreference/xmlconfig.html
<?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">
<!--不加注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!--配置数据库连接 -->
<jdbcConnection
driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ssm1"
userId="root"
password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!--指定Javabean的生成位置,targetProject可以用相对路径,也可以用绝对路径(从盘符开始而不是/服务器) -->
<javaModelGenerator targetPackage="com.ali.clc.bean" targetProject="src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!--指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.ali.clc.mapper" targetProject="resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!--指定mapper接口生成的位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.ali.clc.dao" targetProject="src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!--指定每个表的生成策略,后面四个enablexxx表示不生成XxxExample类 -->
<table tableName="user" domainObjectName="User"
enableCountByExample="false"
enableDeleteByExample="false"
enableSelectByExample="false"
enableUpdateByExample="false">
<!-- useActualColumnNames的取值
false:(默认)字段userName转成属性username,字段user_name转成属性userName
true:字段userName转成属性userName
-->
<!-- <property name="useActualColumnNames" value="true" /> -->
</table>
</context>
</generatorConfiguration>
三、编写main()
main()编写教程见http:/ffwww.mybatis.org/generator/running/runningWithJava.html
package com.ali.clc.mbg;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class Main {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("src/test/resources/mybatis-generator.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);
}
}
四、运行main()
右击代码-Run As-Java Application,稍等几秒,刷新工程,即可查看生成的代码。