深入浅出Mybatis(九)逆向工程

一,    前一篇博客中,介绍了一下Mybatis和hibernate的对比,在这一篇博客说说mybatis的逆向工程,展示一下,只要有一个数据库,你的持久层,你的D层从此不用你自己手写了。

二、什么是逆向工程?


      mybaits需要程序员自己编写sql语句,mybatis官方提供逆向工程 可以针对单表自动生成mybatis执行所需要的代码(mapper.java,mapper.xml、pojo),企业实际开发中,常用的逆向工程方式:由于数据库的表生成java代码。

三、Mybatis中逆向工程的使用

导入

  • 导入已有的数据库,小编已经导入自己编写好的数据库,数据库结构如下:

把generatorSqlmapCustom JavaProject导入

修改配置文件的数据库连接以及数据库

指定数据库表

生成表对应的实体类

1
2
3
4
5
6
7
<javaModelGenerator targetPackage="com.dtt.mybatis.pojo"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
</javaModelGenerator>

 mapper映射文件生成

1
2
3
4
5
6
<!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.dtt.mybatis.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

 

 mapper接口生成

1
2
3
4
5
6
7
<!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.dtt.mybatis.mapper"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

 

     几个关键属性:

      javaModelGenerator :实体类生成;

      sqlMapGenerator :映射文件生成;

      javaClientGenerator :接口生成;

      targetProject:生成文件的位置,本例中.\src,是指src下的目录;

      targetPackage:生成包的名称;

修改完成后,运行GeneratorSqlmap.java中的main方法,就可以生成。

 以User表为例,展示生成的代码:

  • User.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    package com.dtt.mybatis.pojo;
     
    import java.util.Date;
     
    public class User {
        private Integer id;
     
        private String username;
     
        private Date birthday;
     
        private String sex;
     
        private String address;
     
        public Integer getId() {
            return id;
        }
     
        public void setId(Integer id) {
            this.id = id;
        }
     
        public String getUsername() {
            return username;
        }
     
        public void setUsername(String username) {
            this.username = username == null ? null : username.trim();
        }
     
        public Date getBirthday() {
            return birthday;
        }
     
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
     
        public String getSex() {
            return sex;
        }
     
        public void setSex(String sex) {
            this.sex = sex == null ? null : sex.trim();
        }
     
        public String getAddress() {
            return address;
        }
     
        public void setAddress(String address) {
            this.address = address == null ? null : address.trim();
        }
    }
    • UserMapper.java

          这里生成了所有的增删改查的sql语句,调用的时候就直接使用对应的方法就可以了很方便吧。(重点学习一下自动生成的代码是如何封装的)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    package com.dtt.mybatis.mapper;
     
    import com.dtt.mybatis.pojo.User;
    import com.dtt.mybatis.pojo.UserExample;
    import java.util.List;
    import org.apache.ibatis.annotations.Param;
     
    public interface UserMapper {
        int countByExample(UserExample example);
     
        int deleteByExample(UserExample example);
     
        int deleteByPrimaryKey(Integer id);
     
        int insert(User record);
     
        int insertSelective(User record);
     
        List<User> selectByExample(UserExample example);
     
        User selectByPrimaryKey(Integer id);
     
        int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);
     
        int updateByExample(@Param("record") User record, @Param("example") UserExample example);
     
        int updateByPrimaryKeySelective(User record);
     
        int updateByPrimaryKey(User record);
    }

     

     UserMapper.xml

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

    小结

          逆向工程在很多软件里面都有,比如EA的逆向工程,PB的逆向工程。还有很多,总之,这个就是其中的一些很有价值的东西,在企业运用的时候很方便,而且这些生成好的类,尽量不要去修改,如果非要修改的话,可以用pv类来实现继承拓展。这是很好的选择。

     

     

 

posted @   palyer  阅读(314)  评论(0编辑  收藏  举报
编辑推荐:
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
阅读排行:
· C# 13 中的新增功能实操
· Ollama本地部署大模型总结
· 2025成都.NET开发者Connect圆满结束
· langchain0.3教程:从0到1打造一个智能聊天机器人
· 用一种新的分类方法梳理设计模式的脉络
点击右上角即可分享
微信分享提示