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

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

二、什么是逆向工程?


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

三、Mybatis中逆向工程的使用

导入

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

把generatorSqlmapCustom JavaProject导入

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

指定数据库表

生成表对应的实体类

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

 mapper映射文件生成

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

 

 mapper接口生成

<!-- 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
    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语句,调用的时候就直接使用对应的方法就可以了很方便吧。(重点学习一下自动生成的代码是如何封装的)

    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

    <?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 @ 2018-11-01 18:40  palyer  阅读(312)  评论(0编辑  收藏  举报