一、引言
对于使用 Mybatis 的开发者来说,绑定 Xml 和 Dao 接口的对应关系,需要在 Mybatis 的全局配置文件中进行配置,每个 Sql 也需要自己来逐一编写。但 Mybatis 也提供了逆向工程来生成这些文件,可以根据 Database 来逆向的生成这些文件,下面来介绍一下。下面附上 Mybatis Generator 的官方文档,也可以参考着看一下。
http://www.mybatis.org/generator/configreference/xmlconfig.html
二、使用
(1)、maven工程下,加入jar的配置,不是maven工程的话,要下载相应的jar包
(2)、在项目目录下创建mybatisGenerator.xml配置文件,具体配置如下图:
(3)、编写mybatisGenerator.xml的测试代码:
运行上面的测试代码,就可以逆向生成 Mybatis 的实体类、Dao接口文件和mapper文件,但此方式生成的文件并不完整,可以根据功能的需要对文件进行改写。
三、详细代码 (1)、mybatisGenerator.xml代码<generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://124.207.3.80:3308/ble" userId="ble" password="b8w_&8UaW21%,8"> <javaModelGenerator targetPackage="com.scorpios.bean" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> <sqlMapGenerator targetPackage="mapper" targetProject=".\src\main\resources"> <property name="enableSubPackages" value="true" /> <javaClientGenerator type="XMLMAPPER" targetPackage="com.scorpios.dao" targetProject=".\src\main\java"> <property name="enableSubPackages" value="true" /> <table tableName="user_cert_his" domainObjectName="UserCertHis" > public static void main(String[] args) throws Exception { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("mybatisGenerator.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); } }(3)、目录结构图