在上一篇博客中说到,Mybatis是灵活的SQL语句应用,不想Hibernate一样有其封装好的方法,那么,当我们用Mybatis的时候(Hibernate),我们都需要编写其实体类,和配置文件。本篇博客,就介绍一下Mybatis的逆向生成工具。

一、思路

回想一下,在最早运用EF的时候,我们首先通过可视化界面,连接数据库,然后选择要使用的表单,然后,我们就可以自动生成实体类。在运用Hibernate的时候,我们可以先编写Hibernate的配置文件,连接数据库,然后编写实体类文件,然后通过读取HIbernate的配置文件,正向生成数据库表单。然后我们也可以运用工具,从数据库表,生成HIbernate的实体。那么,到了Mybatis这儿,可以怎么做呢?思路如下:

1,连接数据库,指定表单生成

2,指定代码生成后的存放路径,以及要生成哪些代码

2,读取配置文件,生成代码

二、实现

首先是建立了一个Java project,然后引入了5个jar包,分别是:

log4j-1.2.16.jar;Mybatis-3.2.3.jar;Mybatis-generator-core-1.3.2.jar;mysal-connector-java-5.1.28-bin.jar;ojdbc14.jar

版本可以自行确定!

然后,编写mybatis.xml配置文件,代码内容如下:

  1. <span style="font-family:KaiTi_GB2312;font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE generatorConfiguration
  3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
  5.  
  6. <generatorConfiguration>
  7. <context id="testTables" targetRuntime="MyBatis3">
  8. <commentGenerator>
  9. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
  10. <property name="suppressAllComments" value="true" />
  11. </commentGenerator>
  12. <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
  13. <jdbcConnection driverClass="com.mysql.jdbc.Driver"
  14. connectionURL="jdbc:mysql://localhost:3306/Test" userId="root"
  15. password="Angel0626">
  16. </jdbcConnection>
  17. <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和
  18. NUMERIC 类型解析为java.math.BigDecimal -->
  19. <javaTypeResolver>
  20. <property name="forceBigDecimals" value="false" />
  21. </javaTypeResolver>
  22.  
  23. <!-- targetProject:生成PO类的位置 -->
  24. <javaModelGenerator targetPackage="pojo"
  25. targetProject=".\src">
  26. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  27. <property name="enableSubPackages" value="false" />
  28. <!-- 从数据库返回的值被清理前后的空格 -->
  29. <property name="trimStrings" value="true" />
  30. </javaModelGenerator>
  31. <!-- targetProject:mapper映射文件生成的位置 -->
  32. <sqlMapGenerator targetPackage="mapper"
  33. targetProject=".\src">
  34. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  35. <property name="enableSubPackages" value="false" />
  36. </sqlMapGenerator>
  37. <!-- targetPackage:mapper接口生成的位置 -->
  38. <javaClientGenerator type="XMLMAPPER"
  39. targetPackage="mapper"
  40. targetProject=".\src">
  41. <!-- enableSubPackages:是否让schema作为包的后缀 -->
  42. <property name="enableSubPackages" value="false" />
  43. </javaClientGenerator>
  44. <!-- 指定数据库表 -->
  45. <table schema="" tableName="tb_content"></table>
  46. <table schema="" tableName="tb_content_category"></table>
  47. <table schema="" tableName="tb_item"></table>
  48. <table schema="" tableName="tb_item_cat"></table>
  49. <table schema="" tableName="tb_item_desc"></table>
  50. <table schema="" tableName="tb_item_param"></table>
  51. <table schema="" tableName="tb_item_param_item"></table>
  52. <table schema="" tableName="tb_order"></table>
  53. <table schema="" tableName="tb_order_item"></table>
  54. <table schema="" tableName="tb_order_shipping"></table>
  55. <table schema="" tableName="tb_user"></table>
  56.  
  57. </context>
  58. </generatorConfiguration>
  59. </span>

其次,编写实现方法,代码如下:

  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">package test;
  2.  
  3. import java.io.File;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6.  
  7. import org.mybatis.generator.api.MyBatisGenerator;
  8. import org.mybatis.generator.config.Configuration;
  9. import org.mybatis.generator.config.xml.ConfigurationParser;
  10. import org.mybatis.generator.internal.DefaultShellCallback;
  11.  
  12. public class GeneratorSqlmap {
  13.  
  14. public void generator() throws Exception{
  15.  
  16. List<String> warnings=new ArrayList<String>();
  17. boolean overwrite=true;
  18.  
  19. File configFile=new File("mybatis.xml");
  20. ConfigurationParser cp=new ConfigurationParser(warnings);
  21. Configuration config=cp.parseConfiguration(configFile);
  22. DefaultShellCallback callback=new DefaultShellCallback(overwrite);
  23. MyBatisGenerator myBatisGenerator=new MyBatisGenerator(config,callback,warnings);
  24. myBatisGenerator.generate(null);
  25.  
  26. }
  27.  
  28. public static void main(String[] args) throws Exception{
  29. try{
  30. GeneratorSqlmap generatorSqlmap=new GeneratorSqlmap();
  31. generatorSqlmap.generator();
  32. }catch(Exception e){
  33. e.printStackTrace();
  34. }
  35. }
  36.  
  37. }
  38. </span>

运行其main方法,即可生成相应代码。

代码示例:以TbUser表为例:

实体类:

  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">public class TbUser {
  2. private Long id;
  3.  
  4. private String username;
  5.  
  6. private String password;
  7.  
  8. private String phone;
  9.  
  10. private String email;
  11.  
  12. private Date created;
  13.  
  14. private Date updated;
  15.  
  16. public Long getId() {
  17. return id;
  18. }
  19.  
  20. public void setId(Long id) {
  21. this.id = id;
  22. }</span>

mapper接口:

  1. <span style="font-family:KaiTi_GB2312;font-size:18px;">package mapper;
  2.  
  3. import java.util.List;
  4. import org.apache.ibatis.annotations.Param;
  5. import pojo.TbUser;
  6. import pojo.TbUserExample;
  7.  
  8. public interface TbUserMapper {
  9. int countByExample(TbUserExample example);
  10.  
  11. int deleteByExample(TbUserExample example);
  12.  
  13. int deleteByPrimaryKey(Long id);
  14.  
  15. int insert(TbUser record);
  16.  
  17. int insertSelective(TbUser record);
  18.  
  19. List<TbUser> selectByExample(TbUserExample example);
  20.  
  21. TbUser selectByPrimaryKey(Long id);
  22.  
  23. int updateByExampleSelective(@Param("record") TbUser record, @Param("example") TbUserExample example);
  24.  
  25. int updateByExample(@Param("record") TbUser record, @Param("example") TbUserExample example);
  26.  
  27. int updateByPrimaryKeySelective(TbUser record);
  28.  
  29. int updateByPrimaryKey(TbUser record);
  30. }</span>

mapper.xml实现:

  1. <span style="font-family:KaiTi_GB2312;font-size:18px;"><?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="mapper.TbUserMapper" >
  4. <resultMap id="BaseResultMap" type="pojo.TbUser" >
  5. <id column="id" property="id" jdbcType="BIGINT" />
  6. <result column="username" property="username" jdbcType="VARCHAR" />
  7. <result column="password" property="password" jdbcType="VARCHAR" />
  8. <result column="phone" property="phone" jdbcType="VARCHAR" />
  9. <result column="email" property="email" jdbcType="VARCHAR" />
  10. <result column="created" property="created" jdbcType="TIMESTAMP" />
  11. <result column="updated" property="updated" jdbcType="TIMESTAMP" />
  12. </resultMap>
  13. <sql id="Example_Where_Clause" >
  14. <where >
  15. <foreach collection="oredCriteria" item="criteria" separator="or" >
  16. <if test="criteria.valid" >
  17. <trim prefix="(" suffix=")" prefixOverrides="and" >
  18. <foreach collection="criteria.criteria" item="criterion" >
  19. <choose >
  20. <when test="criterion.noValue" >
  21. and ${criterion.condition}
  22. </when>
  23. <when test="criterion.singleValue" >
  24. and ${criterion.condition} #{criterion.value}
  25. </when>
  26. <when test="criterion.betweenValue" >
  27. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  28. </when>
  29. <when test="criterion.listValue" >
  30. and ${criterion.condition}
  31. <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
  32. #{listItem}
  33. </foreach>
  34. </when>
  35. </choose>
  36. </foreach>
  37. </trim>
  38. </if>
  39. </foreach>
  40. </where>
  41. </sql>
  42. <sql id="Update_By_Example_Where_Clause" >
  43. <where >
  44. <foreach collection="example.oredCriteria" item="criteria" separator="or" >
  45. <if test="criteria.valid" >
  46. <trim prefix="(" suffix=")" prefixOverrides="and" >
  47. <foreach collection="criteria.criteria" item="criterion" >
  48. <choose >
  49. <when test="criterion.noValue" >
  50. and ${criterion.condition}
  51. </when>
  52. <when test="criterion.singleValue" >
  53. and ${criterion.condition} #{criterion.value}
  54. </when>
  55. <when test="criterion.betweenValue" >
  56. and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
  57. </when>
  58. <when test="criterion.listValue" >
  59. and ${criterion.condition}
  60. <foreach collection="criterion.value" item="listItem" open="(" close=")" separator="," >
  61. #{listItem}
  62. </foreach>
  63. </when>
  64. </choose>
  65. </foreach>
  66. </trim>
  67. </if>
  68. </foreach>
  69. </where>
  70. </sql>
  71. <sql id="Base_Column_List" >
  72. id, username, password, phone, email, created, updated
  73. </sql>
  74. <select id="selectByExample" resultMap="BaseResultMap" parameterType="pojo.TbUserExample" >
  75. select
  76. <if test="distinct" >
  77. distinct
  78. </if>
  79. <include refid="Base_Column_List" />
  80. from tb_user
  81. <if test="_parameter != null" >
  82. <include refid="Example_Where_Clause" />
  83. </if>
  84. <if test="orderByClause != null" >
  85. order by ${orderByClause}
  86. </if>
  87. </select>
  88. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
  89. select
  90. <include refid="Base_Column_List" />
  91. from tb_user
  92. where id = #{id,jdbcType=BIGINT}
  93. </select>
  94. <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
  95. delete from tb_user
  96. where id = #{id,jdbcType=BIGINT}
  97. </delete>
  98. <delete id="deleteByExample" parameterType="pojo.TbUserExample" >
  99. delete from tb_user
  100. <if test="_parameter != null" >
  101. <include refid="Example_Where_Clause" />
  102. </if>
  103. </delete>
  104. <insert id="insert" parameterType="pojo.TbUser" >
  105. insert into tb_user (id, username, password,
  106. phone, email, created,
  107. updated)
  108. values (#{id,jdbcType=BIGINT}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
  109. #{phone,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR}, #{created,jdbcType=TIMESTAMP},
  110. #{updated,jdbcType=TIMESTAMP})
  111. </insert>
  112. <insert id="insertSelective" parameterType="pojo.TbUser" >
  113. insert into tb_user
  114. <trim prefix="(" suffix=")" suffixOverrides="," >
  115. <if test="id != null" >
  116. id,
  117. </if>
  118. <if test="username != null" >
  119. username,
  120. </if>
  121. <if test="password != null" >
  122. password,
  123. </if>
  124. <if test="phone != null" >
  125. phone,
  126. </if>
  127. <if test="email != null" >
  128. email,
  129. </if>
  130. <if test="created != null" >
  131. created,
  132. </if>
  133. <if test="updated != null" >
  134. updated,
  135. </if>
  136. </trim>
  137. <trim prefix="values (" suffix=")" suffixOverrides="," >
  138. <if test="id != null" >
  139. #{id,jdbcType=BIGINT},
  140. </if>
  141. <if test="username != null" >
  142. #{username,jdbcType=VARCHAR},
  143. </if>
  144. <if test="password != null" >
  145. #{password,jdbcType=VARCHAR},
  146. </if>
  147. <if test="phone != null" >
  148. #{phone,jdbcType=VARCHAR},
  149. </if>
  150. <if test="email != null" >
  151. #{email,jdbcType=VARCHAR},
  152. </if>
  153. <if test="created != null" >
  154. #{created,jdbcType=TIMESTAMP},
  155. </if>
  156. <if test="updated != null" >
  157. #{updated,jdbcType=TIMESTAMP},
  158. </if>
  159. </trim>
  160. </insert>
  161. <select id="countByExample" parameterType="pojo.TbUserExample" resultType="java.lang.Integer" >
  162. select count(*) from tb_user
  163. <if test="_parameter != null" >
  164. <include refid="Example_Where_Clause" />
  165. </if>
  166. </select>
  167. <update id="updateByExampleSelective" parameterType="map" >
  168. update tb_user
  169. <set >
  170. <if test="record.id != null" >
  171. id = #{record.id,jdbcType=BIGINT},
  172. </if>
  173. <if test="record.username != null" >
  174. username = #{record.username,jdbcType=VARCHAR},
  175. </if>
  176. <if test="record.password != null" >
  177. password = #{record.password,jdbcType=VARCHAR},
  178. </if>
  179. <if test="record.phone != null" >
  180. phone = #{record.phone,jdbcType=VARCHAR},
  181. </if>
  182. <if test="record.email != null" >
  183. email = #{record.email,jdbcType=VARCHAR},
  184. </if>
  185. <if test="record.created != null" >
  186. created = #{record.created,jdbcType=TIMESTAMP},
  187. </if>
  188. <if test="record.updated != null" >
  189. updated = #{record.updated,jdbcType=TIMESTAMP},
  190. </if>
  191. </set>
  192. <if test="_parameter != null" >
  193. <include refid="Update_By_Example_Where_Clause" />
  194. </if>
  195. </update>
  196. <update id="updateByExample" parameterType="map" >
  197. update tb_user
  198. set id = #{record.id,jdbcType=BIGINT},
  199. username = #{record.username,jdbcType=VARCHAR},
  200. password = #{record.password,jdbcType=VARCHAR},
  201. phone = #{record.phone,jdbcType=VARCHAR},
  202. email = #{record.email,jdbcType=VARCHAR},
  203. created = #{record.created,jdbcType=TIMESTAMP},
  204. updated = #{record.updated,jdbcType=TIMESTAMP}
  205. <if test="_parameter != null" >
  206. <include refid="Update_By_Example_Where_Clause" />
  207. </if>
  208. </update>
  209. <update id="updateByPrimaryKeySelective" parameterType="pojo.TbUser" >
  210. update tb_user
  211. <set >
  212. <if test="username != null" >
  213. username = #{username,jdbcType=VARCHAR},
  214. </if>
  215. <if test="password != null" >
  216. password = #{password,jdbcType=VARCHAR},
  217. </if>
  218. <if test="phone != null" >
  219. phone = #{phone,jdbcType=VARCHAR},
  220. </if>
  221. <if test="email != null" >
  222. email = #{email,jdbcType=VARCHAR},
  223. </if>
  224. <if test="created != null" >
  225. created = #{created,jdbcType=TIMESTAMP},
  226. </if>
  227. <if test="updated != null" >
  228. updated = #{updated,jdbcType=TIMESTAMP},
  229. </if>
  230. </set>
  231. where id = #{id,jdbcType=BIGINT}
  232. </update>
  233. <update id="updateByPrimaryKey" parameterType="pojo.TbUser" >
  234. update tb_user
  235. set username = #{username,jdbcType=VARCHAR},
  236. password = #{password,jdbcType=VARCHAR},
  237. phone = #{phone,jdbcType=VARCHAR},
  238. email = #{email,jdbcType=VARCHAR},
  239. created = #{created,jdbcType=TIMESTAMP},
  240. updated = #{updated,jdbcType=TIMESTAMP}
  241. where id = #{id,jdbcType=BIGINT}
  242. </update>
  243. </mapper></span>

三、总结

从生成的代码可以看出,生成的代码,基本上解决了对于一个实体操作的增删改查,但是,每个实体的代码都是这样的丰富,还能不能继续往上抽象一层呢?下一篇博客介绍Mybatis的底层封装思路!

【SSM 4】Mybatis逆向生成工具的更多相关文章

  1. 「小程序JAVA实战」Springboot版mybatis逆向生成工具(32)

    转自:https://idig8.com/2018/08/29/xiaochengxujavashizhanspringbootbanmybatisnixiangshengchenggongju32/ ...

  2. Springboot学习与mybatis逆向生成工具

    最近H2数据库越用越觉得方便,在不同办公处无缝继续demo的感觉就是爽.   今天接上一篇Springboot简洁整合mybatis,补上sts(即eclipse)使用mybatis generato ...

  3. myBatis逆向生成及使用

    引入数据库驱动 <!-- mybatis逆向生成包 --><dependency> <groupId>org.mybatis.generator</group ...

  4. Mybatis逆向生成

    在已经有了数据库的表的时候,为了方便起见,我们可以逆向生成javabean,xml,dao接口等,当然,下载mybaits-generation的工具,我这里用的是eclipse插件,然后准备一 个x ...

  5. Mybatis逆向生成使用扩展类

    1.背景介绍 用的mybatis自动生成的插件,然而每次更改数据库的时候重新生成需要替换原有的mapper.xml文件,都要把之前业务相关的sql重新写一遍,感觉十分麻烦,就想着把自动生成的作为一个基 ...

  6. 一步步学Mybatis-告别繁琐的配置之Mybatis配置文件生成工具 (7)

    今年是2013年的杀青之日,前几天由于比较忙,没有及时更新本篇的最后一篇东西,前六篇中我们主要都是采用手动配置相关的Mybatis映射文件与相应的接口类与实体类.当然如果在真正的使用过程中,由于业务的 ...

  7. Mybatis逆向生成代碼

    Idea 单模块 1.在pom.xml中添加依赖 <build> <plugins> <plugin> <groupId>org.mybatis.gen ...

  8. Mybatis Generator生成工具配置文件详解

    <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE generatorConfiguration ...

  9. Mybatis逆向生成Mapper文件

    本文参考博客 http://blog.csdn.net/for_my_life/article/details/51228098 1. 在resources根目录下添加generator.proper ...

随机推荐

  1. js问题

    1.原型链问题 1.js中万物皆对象,但对象也分为普通对象和函数对象,Object,Function都是js自带的函数对象,凡是通过 new Function() 创建的对象都是函数对象,其他的都是普 ...

  2. multithreading - Reader/Writer Locks in C++

    You Only Need To Note This: only 1 single thread can acquire an upgrade_lock at one time. others are ...

  3. 【转】android 属性动画之 ObjectAnimator

    原文网址:http://blog.csdn.net/feiduclear_up/article/details/39255083 前面一篇博客讲解了 android 简单动画之 animtion,这里 ...

  4. Java高级开发工程师面试考纲 转

    转 http://www.sanesee.com/article/java-engineer-interview-of-content-tree 1 Java基础 1.1 Collection和Map ...

  5. PHP MVC简单介绍,对PHP当前主流的MVC做了一个总结

    东抄西抄,对PHP当前主流的MVC做了一个总结PPT. 希望对初学者有点帮助! PHP MVC初步.ppt

  6. C#将exe运行程序嵌入到自己的winform窗体中

    以下例子是将Word打开,然后将它嵌入到winform窗体中,效果如下图:C将exe运行程序嵌入到自己的winform窗体中 - kingmax_res - iSport注意:该方法只适用于com的e ...

  7. MySql 存储过程及调用方法

    存储过程实例: DELIMITER $$drop procedure if exists ff $$CREATE /*[DEFINER = { user | CURRENT_USER }]*/ PRO ...

  8. 数据库MySQL基本语法思维导图

  9. mysql新建表示,时间字段timetamp碰到的问题

    在mysql中创建表时,在新加的字段时间上,碰到下面的问题: 建表语句如下: CREATE TABLE seckill( seckill_id bigint NOT NULL AUTO_INCREME ...

  10. OAF_开发系列16_实现OAF与XML Publisher整合

    http://wenku.baidu.com/link?url=y2SFKHP5qqn4bl_iNeqLGjXsTvhyFuhkMraIbWZdTXbzcv0vTefrZFFBDWie0cAAKuTw ...