1、引入 Maven 坐标
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
2、配置文件
generatorConfig.xml,需要放到maven项目resources或类路径文件夹下
<?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:必选,上下文id,用于在生成错误时提示
targetRuntime:
1,MyBatis3:默认的值,生成QBC风格的CRUD
2,MyBatis3Simple:生成基本的CRUD,简单版
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- 给JavaBean添加Serializable接口 -->
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="false"/>
</commentGenerator>
<!-- 配置数据库连接信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/conmpany"
userId="root"
password="abc123">
</jdbcConnection>
<!-- JavaBean的生成策略 -->
<javaModelGenerator targetPackage="com.atguigu.bean" targetProject="src/main/java">
<!-- 是否允许有子包,targetPackage配置为多级包,故此value=true -->
<property name="enableSubPackages" value="true"/>
<!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- SQL映射文件的生成策略 -->
<sqlMapGenerator targetPackage="com.atguigu.mapper" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- mapper接口的生成策略 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.atguigu.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 逆向分析的表 -->
<table tableName="department" domainObjectName="Department"></table>
<table tableName="employee" domainObjectName="Employee"></table>
</context>
</generatorConfiguration>
3、执行代码
@Test
public void mbg() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File(this.getClass().getClassLoader().getResource("generatorConfig.xml").getFile());
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);
}