mybatis逆向工程-代码生成
Mybatis 是我们经常使用的数据库持久层工具,通过使用 mybatis 可以很方便的完成持久层的操作。但是,问题来了当我们进行大数据表的操作是,我们不可能去手动的去编写Java bean 和重复的 Mapper和配置,因为这太费时间,浪费我们的经历了,这是就需要我们的基本代码生成技术了。当我们开发时,我们也不可避免的需要进行多个数据库操作,这时我们就要学会多数据源的配置。
mybatis 代码生成
- 导入我们所需的jar 包
> 主要是 mybatis 的jar包和 mybatis-gennerator-core 和 数据库驱动jar 包(自行忽略 mybatis 和spring 整合的jar包)
配置用于生成代码的配置文件(generatorConfig.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> <classPathEntry location="mysql-connector-java-5.1.7-bin.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!--是否生成注释--> <property name="suppressAllComments" value="true"/> </commentGenerator> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://182.92.221.190:3306/bookdb" userId="ldy" password="135135ldy"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!--分别对应实体类,Mapper 类,xml 配置文件--> <javaModelGenerator targetPackage="com.hyg.im.model" targetProject="../../../src"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <javaClientGenerator type="XMLMAPPER" targetPackage="com.hyg.im.mapper" targetProject="../../../src"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <sqlMapGenerator targetPackage="com.hyg.im.mapper" targetProject="../../../resource"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 配置要生成的表,可以多个 --> <table tableName="user_info" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> <!--下面这个配置,保证数据库字段与实体类字段保持一致--> <property name="useActualColumnNames" value="true"/> </table> </context> </generatorConfiguration>
通过代码或命令进行代码生成
java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite
至此,大功告成,通过很简单的方式就实现了我们的代码生成。
![](https://i-blog.csdnimg.cn/blog_migrate/f23021b5af4241dd2398015e92f0a48c.png)