Mybatis属于半自动ORM,在使用这个框架中,工做量最大的就是书写Mapping的映射文件,因为手动书写很容易出错,咱们能够利用Mybatis-Generator来帮咱们自动生成文件。经过在Eclipse中集成mybatis-generater插件,自动生成Mybatis相关的pojo、dao、Mapper.xml等文件,可以减小出错,减小开发工做量。java
1、准备工做
Mybatis代码自动生成须要依赖于mybatis generator,Mybatis-Generator提供了eclipse插件。先获取插件,而后安装该插件。
一、获取mybatis generator eclipse插件mysql
能够经过此地址 http://pan.baidu.com/s/1c0cjDEK?errno=0&errmsg=Auth%20Login%20Sucess&&bduss=&ssnerror=0sql
2. 在eclipse中安装插件刚刚下载的插件
数据库
3.找到本身的eclipse安装路径mybatis
4.将获取的eclipse插件解压拷贝到eclipse安装目录app
5.替换后重启eclipse,在eclipse中点击“File”-“New”-“Other”在类型选择栏里能够看到Mybatis目录和MyBatis Generator Configuration File就说明插件已经安装成功了。框架
2、代码生成
1. 在ecplise中新建一个名为MybatisModel 的Dynamic Web Project工程。引入MySQL-connector-Java-5.1.34.jar的mysql驱动包,经过在eclipse中点击“File”-“New”-“Other”在类型选择栏里选择Mybatis目录下的MyBatis Generator Configuration File生成一个generatorConfig.xml的配置文件。dom
2. 打开generatorConfig.xml配置以下:eclipse
<?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> <!-- 数据库驱动 注意:这个 location要指明\MySQL-connector-Java jar包的绝对路径--> <classPathEntry location="C:\Users\hp\.m2\repository\mysql\mysql-connector-java\5.1.34\mysql-connector-java-5.1.34.jar"/> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressDate" value="true"/> <!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true"/> </commentGenerator> <!--数据库连接URL,用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="123456"> </jdbcConnection> <javaTypeResolver> <property name="forceBigDecimals" value="false"/> </javaTypeResolver> <!-- 生成模型的包名和位置 这个targetProject必定不要写错:这里应该是写你的工程名字--> <javaModelGenerator targetPackage="com.yatang.pojo" targetProject="test"> <property name="enableSubPackages" value="true"/> <property name="trimStrings" value="true"/> </javaModelGenerator> <!-- 生成映射文件的包名和位置--> <sqlMapGenerator targetPackage="com.yatang.mapper" targetProject="test"> <property name="enableSubPackages" value="true"/> </sqlMapGenerator> <!-- 生成DAO的包名和位置--> <javaClientGenerator type="XMLMAPPER" targetPackage="com.yatang.dao" targetProject="test"> <property name="enableSubPackages" value="true"/> </javaClientGenerator> <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名--> <table tableName="u_permission" domainObjectName="Upermission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table> </context> </generatorConfiguration>
3. 配置完成后,在generatorConfig.xml的配置文件上点击右键选择“Generate MyBatis/iBATIS Artifacts”就能够生成相应的代码。学习
4. 生成的代码结构以下图所示:
5. Mapper.xml中的单表的增长、修改、删除都已经自动生成了。相应的model和dao层的代码都已经生成了。
6. 剩下要作的就是只须要将生成的代码挪到本身的工程中进行修改调试了。
不足之处请你们指出来 共同窗习 共同进步 ~
-