首先建立一個test類:html
在main方法裏寫上以下代碼:java
List <String> warnings = new ArrayList <String>(); boolean overwrite = true; File configFile = new File("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);
在工程目錄下新建一個generator.xml文件:mysql
開發工具eclipse:git
開發工具idea:github
<?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"></property> </commentGenerator> <!-- 設定數據庫鏈接 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/mybatis" userId="root" password="123"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 生成 bean 存放的位置 --> <javaModelGenerator targetPackage="com.ujiuye.bean" targetProject=".\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 生成的mapper文件的位置 --> <sqlMapGenerator targetPackage="com.ujiuye.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 生成的mapper.xml 對應的那個mapper接口的存放位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.ujiuye.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 設定反向生成的表 --> <table tableName="Person"></table> <table tableName="car"></table> <table tableName="card"></table> </context> </generatorConfiguration>
最後的table標籤是本身數據庫中表的名字;數據庫的鏈接信息須要本身修改sql
執行test類就會自動生成本身以上設置table標籤中數據中表的對應的實體類,dao層接口以及對應的mapper映射數據庫
此外須要的jar包請自行下載:https://github.com/Pei-Qi/mybatis_jarmybatis
原文出處:https://www.cnblogs.com/hwxxbc/p/10486830.htmlapp