MyBatis逆向工程的简单使用

1、什么是MyBatis逆向工程

按照普通的模式,我们建立完数据表之后,需要手动建立与表对应的实体pojo类,然后是dao层,还有映射的sqlMapper.xml配置文件,每一张表,都要建立pojo、dao、sqlMapper.xml,这样就非常的麻烦。

于是MyBatis官方为我们提供了一个逆向工程,通过这个逆向工程,只要建立好数据表,那么MyBatis就会根据这个表自动生成pojo类、dao接口、sql映射文件。也就是说,逆向工程的目的是为了简化开发,加快我们的开发步骤。

2、逆向工程的使用

2.1、创建工程

创建一个Maven工程,建好包:
在这里插入图片描述

2.2、pom依赖

	<dependencies>
		<!-- mysql驱动 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
		</dependency>
		<!-- mybatis依赖 -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.4.6</version>
		</dependency>
		<!-- mybatis逆向工程依赖 -->
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.7</version>
		</dependency>
	</dependen

2.3、配置文件

创建生成所需的配置文件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>
   <context id="DB2Tables" targetRuntime="MyBatis3">
     <!-- 去除生成的注解 -->
     <commentGenerator>
        <property name="suppressAllComments" value="true"/>
     </commentGenerator>
     <!-- 数据库连接配置 -->
     <!-- 注意xml中不支持&,用&amp;代替 -->
     <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" 
     connectionURL="jdbc:mysql://rm-m5e130nm7h37n6v982o.mysql.rds.aliyuncs.com:3306/demo?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=GMT%2B8"
     userId="xxxxx" password="xxxxxx"></jdbcConnection>
     
     <!-- 处理NUMERIC和DECIMAL类型的策略 -->
     <javaTypeResolver>
         <property name="forceBigDecimals" value="false" />
     </javaTypeResolver>
     
     <!-- 配置pojo生成的位置 -->
     <javaModelGenerator targetPackage="com.ycz.pojo"  targetProject="src/main/java">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />
     </javaModelGenerator>
     
     <!-- 配置sql映射文件的生成位置 -->
     <sqlMapGenerator targetPackage="com.ycz.mapper" targetProject="src/main/resources">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />        
     </sqlMapGenerator>
     
     <!-- 配置dao接口的生成位置 -->
     <javaClientGenerator type="XMLMAPPER" targetPackage="com.ycz.dao" 
     targetProject="src/main/java">
        <property name="enableSubPackages" value="true" />
        <property name="trimStrings" value="true" />     
     </javaClientGenerator>
     
     <!-- 指定逆向依据的数据表 -->
     <table tableName="person" domainObjectName="Person"></table>
   </context>
 </generatorConfiguration>

注意:这个配置文件中,各个元素标签出现的位置是有要求的,位置不对会报错。

2.4、生成程序

创建一个生成的程序:

public class GeneratorTest {
    
    public static void main(String[] args) throws Exception {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("src/main/resources/generatorConfig.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
        System.out.println("生成成功!");
    }

}

2.5、测试

运行生成程序:
在这里插入图片描述
查看pojo包:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
可以看到生成了一个Person类和PersonExample类,并且有get和set方法。

查看dao包:
在这里插入图片描述
生成了一个接口:
在这里插入图片描述
这个接口中自动定义了一些常用的简单方法。

查看sql映射文件:
在这里插入图片描述

<?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.ycz.dao.PersonMapper">
  <resultMap id="BaseResultMap" type="com.ycz.pojo.Person">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    <result column="address" jdbcType="VARCHAR" property="address" />
    <result column="age" jdbcType="INTEGER" property="age" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <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 close=")" collection="criterion.value" item="listItem" open="(" 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="(" prefixOverrides="and" suffix=")">
            <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 close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    id, name, password, address, age
  </sql>
  <select id="selectByExample" parameterType="com.ycz.pojo.PersonExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from person
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from person
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from person
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.ycz.pojo.PersonExample">
    delete from person
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.ycz.pojo.Person">
    insert into person (id, name, password, 
      address, age)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
      #{address,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.ycz.pojo.Person">
    insert into person
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="name != null">
        name,
      </if>
      <if test="password != null">
        password,
      </if>
      <if test="address != null">
        address,
      </if>
      <if test="age != null">
        age,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="name != null">
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        #{age,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.ycz.pojo.PersonExample" resultType="java.lang.Long">
    select count(*) from person
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update person
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.name != null">
        name = #{record.name,jdbcType=VARCHAR},
      </if>
      <if test="record.password != null">
        password = #{record.password,jdbcType=VARCHAR},
      </if>
      <if test="record.address != null">
        address = #{record.address,jdbcType=VARCHAR},
      </if>
      <if test="record.age != null">
        age = #{record.age,jdbcType=INTEGER},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update person
    set id = #{record.id,jdbcType=INTEGER},
      name = #{record.name,jdbcType=VARCHAR},
      password = #{record.password,jdbcType=VARCHAR},
      address = #{record.address,jdbcType=VARCHAR},
      age = #{record.age,jdbcType=INTEGER}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.ycz.pojo.Person">
    update person
    <set>
      <if test="name != null">
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        address = #{address,jdbcType=VARCHAR},
      </if>
      <if test="age != null">
        age = #{age,jdbcType=INTEGER},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.ycz.pojo.Person">
    update person
    set name = #{name,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

里面是与接口方法对应的SQL语句。如果有需要的话,可以自己添加新的方法和SQL语句。

3、逆向工程的优缺点

  • 优点:帮助我们自动生成Java代码,大大加快了我们的开发效率。
  • 缺点:生成的文件太过冗余,不必要的代码过多。尤其是sql映射文件,里面的配置内容太多,对于dao层,提供的方法比较有限,需要自行扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值