详细步骤可参考官方文档:http://www.mybatis.org/generator/
1. 添加MyBatis Generator jar 包:
链接:https://pan.baidu.com/s/1ZqlKR-l8kaohsxiyUmZG1A
提取码:30ul
2. 编写用来完成 MyBatis 逆向工程的配置文件 mbg.xml:
其中,targetPackage 指定生成相应文件的包名,targetProject 指定包所在工程位置
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE generatorConfiguration 3 PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 6 <generatorConfiguration> 7 <context id="DB2Tables" targetRuntime="MyBatis3"> 8 <commentGenerator> 9 <property name="suppressAllComments" value="true"/> 10 </commentGenerator> 11 <!-- 配置数据库连接信息 --> 12 <jdbcConnection driverClass="com.mysql.jdbc.Driver" 13 connectionURL="jdbc:mysql://localhost:3306/db" 14 userId="root" 15 password="123456"> 16 </jdbcConnection> 17 18 <javaTypeResolver > 19 <property name="forceBigDecimals" value="false" /> 20 </javaTypeResolver> 21 22 <!-- 指定 JavaBean 生成的位置 --> 23 <javaModelGenerator 24 targetPackage="com.lvey.crud.vo" 25 targetProject=".\src\main\java"> 26 <property name="enableSubPackages" value="true" /> 27 <property name="trimStrings" value="true" /> 28 </javaModelGenerator> 29 30 <!-- 指定 sql映射文件生成的位置 --> 31 <sqlMapGenerator 32 targetPackage="mapper" 33 targetProject=".\src\main\resources"> 34 <property name="enableSubPackages" value="true" /> 35 </sqlMapGenerator> 36 37 <!-- 指定 dao接口生成的位置 --> 38 <javaClientGenerator type="XMLMAPPER" 39 targetPackage="com.lvey.crud.dao" 40 targetProject=".\src\main\java"> 41 <property name="enableSubPackages" value="true" /> 42 </javaClientGenerator> 43 44 <!-- 指定每个表对应的生成策略 --> 45 <table tableName="tb_employee" domainObjectName="Employee"/> 46 <table tableName="tb_department" domainObjectName="Department"/> 47 </context> 48 </generatorConfiguration>
3. 新建一个Java测试类,使用 Java 程序配合配置文件完成 MyBatis 逆向工程:
1 public class MBGTest { 2 3 public static void main(String[] args) throws IOException, XMLParserException, SQLException, InterruptedException, InvalidConfigurationException { 4 List<String> warnings = new ArrayList<String>(); 5 boolean overwrite = true; 6 File configFile = new File("mbg.xml"); 7 ConfigurationParser cp = new ConfigurationParser(warnings); 8 Configuration config = cp.parseConfiguration(configFile); 9 DefaultShellCallback callback = new DefaultShellCallback(overwrite); 10 MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); 11 myBatisGenerator.generate(null); 12 } 13 }