个人博客地址:https://alexaccele.github.io/
首先需要有一个.xml的配置文件
例如mbg.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>
<!--
targetRuntime="MyBatis3Simple":生成简单版的CRUD
MyBatis3:豪华版
-->
<context id="DB2Tables" targetRuntime="MyBatis3">
<!-- jdbcConnection:指定如何连接到目标数据库 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis_generator"
userId="root"
password="123456">
</jdbcConnection>
<!-- java类型解析器
是否强制转换BigDecimals-->
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- javaModelGenerator:指定javaBean的生成策略,会根据已经创建的数据库进行javabean的生成
targetPackage:指定生成的javabean的位置
targetProject:指定目标工程
-->
<javaModelGenerator targetPackage="com.example.mybatis.bean"
targetProject=".\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- sqlMapGenerator:sql映射生成策略:
targetPackage:指定生成的dao的位置
targetProject:指定目标工程所在位置
以下实例会在conf/com/example/mybatis/dao包下生成数据库中对应的*mapper.xml文件,其中就写好了SQL语句
-->
<sqlMapGenerator targetPackage="com.example.mybatis.dao"
targetProject=".\conf">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<!-- javaClientGenerator:指定mapper接口所在的位置,以下实例会在
src/com/example/mybatis/dao路径下生成对应的*Mapper.java的mapper接口
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mybatis.dao"
targetProject=".\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<!-- 指定要逆向分析哪些表:根据表要创建javaBean -->
<table tableName="tbl_dept" domainObjectName="Department"></table>
<table tableName="tbl_employee" domainObjectName="Employee"></table>
</context>
</generatorConfiguration>
注意:需要导入mybatis逆向工程的jar包:mybatis-generator-core.jar
运行以下代码
可以在测试类中运行,只有能够在工程内运行以下代码就可以
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.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);
运行完成后,此时刷新工程就会看到工程中有对应的javabean和dao以及mapper等文件生成了。
最后在这里给出官方文档的地址:http://www.mybatis.org/generator/quickstart.html,更多的生成方式和配置在文档中都有更加详尽的描述。