Java - MyBites 逆向工程
逆向工程是什么呢? 说白了就是 mybatis 中提供了一个可以让你从 已经创建好的 数据库中,去通过表名,生成对应类,类属性和XML文件(sql语句)。
开始配置:
1. src 下创建 generator.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> <context id="mysqlTables" targetRuntime="MyBatis3"> <!--数据库配置--> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/table_name" userId="root" password=""> </jdbcConnection> <!-- java类型解析 --> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 模型生成包名--> <javaModelGenerator targetPackage="com.q.backoffice.model" targetProject=".\src"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- mybatis的映射.xml--> <sqlMapGenerator targetPackage="com.q.backoffice.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- mybatis 的mapper接口生成的包路径--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.q.backoffice.mapper" targetProject=".\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 配置生成表的模型--> <table tableName="items"/> <table tableName="orderdetail" domainObjectName="OrderDetail"></table> <table tableName="orders"></table> <table tableName="user"></table> </context> </generatorConfiguration>
2. 创建一个类,并编写生成代码,运行后即可生成完毕
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; import java.io.File; import java.util.ArrayList; import java.util.List; public class Generator { public static void main(String[] args)throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("src/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); } }