项目的model一旦多了起来,复杂了起来,我们很自然的想到使用mybatis的逆向工程来生成相应的pojo和mapper,能节省很多精力。

  

  MyBatis Generator(MBG)是 MyBatis 和 iBATIS 的代码生成工具。它可以为所有 MyBatis
版本以及 iBATIS 版本 2.2.0 及以上自动生成代码。
  它会逆向查找一张或多张数据库表的信息,生成操作数据库表所需要的组件。基本上省去了
自已手动创建实体类以及配置文件的麻烦。
  MBG 只是对单表的增删改查(CRUD (Create, Retrieve, Update, Delete))生成了大部分的代
码,对于像连接查询或者存储过程之类的,还是需要手动编写 sql 和实体类的。MBG 会生成对应于表结构的 java POJO 类。包括一个支持动态查询、更新和删除的类。
    
 
MBG 为单表的增删改查生成了配置文件和映射文件。
 
生成的 SQL 语句包括:
insert
update by primary key
update by example (使用动态 where 子句)
delete by primary key
delete by example (使用动态 where 子句)
select by primary key
select by example (使用动态 where 子句)
select by exampleWithBLOBS  (含有大字段(text)的where)
count by example
 
mybatis的排序问题
 
mybatis逆向工程介绍

 

 

 
根据表结构的不同,这些语句会有一些变化,比如有的表没有主键,则 MBG 不会生成根据主键更新表的记录的方法。
 
 
 
 

2.1 建立 MybatisGenerator 项目

 
建立 Java 项目即可
 

2.2 添加 jar 包支持

 mybatis逆向工程介绍

 

 

2.3 建立配置文件

<?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="testTables" targetRuntime="MyBatis3"> <commentGenerator>
<!-- 是否去除自动生成的注释 true:是 : false:否 --> <property name="suppressAllComments" value="true" />
</commentGenerator>
<!--数据库连接的信息:驱动类、连接地址、用户名、密码 --> <jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://192.168.30.10:3306/ego" userId="root"
password="root">
</jdbcConnection>
<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时 把JDBC DECIMAL 和
NUMERIC 类型解析为java.math.BigDecimal --> <javaTypeResolver> <property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- targetProject:生成POJO类的位置 --> <javaModelGenerator targetPackage="com.bjsxt.ego.rpc.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" />
<!-- 从数据库返回的值被清理前后的空格 --> <property name="trimStrings" value="true" />
</javaModelGenerator>
<!-- targetProject:mapper映射文件生成的位置 --> <sqlMapGenerator targetPackage="com.bjsxt.ego.rpc.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" />
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 --> <javaClientGenerator type="XMLMAPPER"
targetPackage="com.bjsxt.ego.rpc.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schema作为包的后缀 --> <property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- 指定数据库表 --> <table schema="" tableName="tb_content"></table> <table schema="" tableName="tb_content_category"></table> <table schema="" tableName="tb_item"></table> <table schema="" tableName="tb_item_cat"></table> <table schema="" tableName="tb_item_desc"></table> <table schema="" tableName="tb_item_param"></table> <table schema="" tableName="tb_item_param_item"></table> <table schema="" tableName="tb_order"></table> <table schema="" tableName="tb_order_item"></table> <table schema="" tableName="tb_order_shipping"></table> <table schema="" tableName="tb_user"></table>
</context>
</generatorConfiguration>

2.4 建立项目启动类

 

mybatis逆向工程介绍
package com.mybatis.generator.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class MybatisGeneratorTest {
public void generator() throws Exception {
List<String>warnings = new ArrayList<String>();
boolean overwrite = true;
// 指定 逆向工程配置文件
File configFile = new
File(System.getProperty("user.dir")+"/src/config.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);
}
public static void main(String[] args) throws Exception {
try {
MybatisGeneratorTest generatorSqlmap = new MybatisGeneratorTest();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
} } }
View Code

 

 

 

 

mybatis逆向工程

 

 

 

2.5 生成的mapper

mybatis逆向工程介绍
package com.bjsxt.ego.rpc.mapper;

import com.bjsxt.ego.rpc.pojo.TbItem;
import com.bjsxt.ego.rpc.pojo.TbItemExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface TbItemMapper {
    int countByExample(TbItemExample example);

    int deleteByExample(TbItemExample example);

    int deleteByPrimaryKey(Long id);

    int insert(TbItem record);

    int insertSelective(TbItem record);

    List<TbItem> selectByExample(TbItemExample example);

    TbItem selectByPrimaryKey(Long id);

    int updateByExampleSelective(@Param("record") TbItem record, @Param("example") TbItemExample example);

    int updateByExample(@Param("record") TbItem record, @Param("example") TbItemExample example);

    int updateByPrimaryKeySelective(TbItem record);

    int updateByPrimaryKey(TbItem record);
}
View Code
mybatis逆向工程介绍
<?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.bjsxt.ego.rpc.mapper.TbItemMapper" >
  <resultMap id="BaseResultMap" type="com.bjsxt.ego.rpc.pojo.TbItem" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="sell_point" property="sellPoint" jdbcType="VARCHAR" />
    <result column="price" property="price" jdbcType="BIGINT" />
    <result column="num" property="num" jdbcType="INTEGER" />
    <result column="barcode" property="barcode" jdbcType="VARCHAR" />
    <result column="image" property="image" jdbcType="VARCHAR" />
    <result column="cid" property="cid" jdbcType="BIGINT" />
    <result column="status" property="status" jdbcType="TINYINT" />
    <result column="created" property="created" jdbcType="TIMESTAMP" />
    <result column="updated" property="updated" jdbcType="TIMESTAMP" />
  </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, title, sell_point, price, num, barcode, image, cid, status, created, updated
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.bjsxt.ego.rpc.pojo.TbItemExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    <include refid="Base_Column_List" />
    from tb_item
    <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.Long" >
    select 
    <include refid="Base_Column_List" />
    from tb_item
    where id = #{id,jdbcType=BIGINT}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from tb_item
    where id = #{id,jdbcType=BIGINT}
  </delete>
  <delete id="deleteByExample" parameterType="com.bjsxt.ego.rpc.pojo.TbItemExample" >
    delete from tb_item
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.bjsxt.ego.rpc.pojo.TbItem" >
    insert into tb_item (id, title, sell_point, 
      price, num, barcode, 
      image, cid, status, 
      created, updated)
    values (#{id,jdbcType=BIGINT}, #{title,jdbcType=VARCHAR}, #{sellPoint,jdbcType=VARCHAR}, 
      #{price,jdbcType=BIGINT}, #{num,jdbcType=INTEGER}, #{barcode,jdbcType=VARCHAR}, 
      #{image,jdbcType=VARCHAR}, #{cid,jdbcType=BIGINT}, #{status,jdbcType=TINYINT}, 
      #{created,jdbcType=TIMESTAMP}, #{updated,jdbcType=TIMESTAMP})
  </insert>
  <insert id="insertSelective" parameterType="com.bjsxt.ego.rpc.pojo.TbItem" >
    insert into tb_item
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        id,
      </if>
      <if test="title != null" >
        title,
      </if>
      <if test="sellPoint != null" >
        sell_point,
      </if>
      <if test="price != null" >
        price,
      </if>
      <if test="num != null" >
        num,
      </if>
      <if test="barcode != null" >
        barcode,
      </if>
      <if test="image != null" >
        image,
      </if>
      <if test="cid != null" >
        cid,
      </if>
      <if test="status != null" >
        status,
      </if>
      <if test="created != null" >
        created,
      </if>
      <if test="updated != null" >
        updated,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="title != null" >
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="sellPoint != null" >
        #{sellPoint,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        #{price,jdbcType=BIGINT},
      </if>
      <if test="num != null" >
        #{num,jdbcType=INTEGER},
      </if>
      <if test="barcode != null" >
        #{barcode,jdbcType=VARCHAR},
      </if>
      <if test="image != null" >
        #{image,jdbcType=VARCHAR},
      </if>
      <if test="cid != null" >
        #{cid,jdbcType=BIGINT},
      </if>
      <if test="status != null" >
        #{status,jdbcType=TINYINT},
      </if>
      <if test="created != null" >
        #{created,jdbcType=TIMESTAMP},
      </if>
      <if test="updated != null" >
        #{updated,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.bjsxt.ego.rpc.pojo.TbItemExample" resultType="java.lang.Integer" >
    select count(*) from tb_item
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update tb_item
    <set >
      <if test="record.id != null" >
        id = #{record.id,jdbcType=BIGINT},
      </if>
      <if test="record.title != null" >
        title = #{record.title,jdbcType=VARCHAR},
      </if>
      <if test="record.sellPoint != null" >
        sell_point = #{record.sellPoint,jdbcType=VARCHAR},
      </if>
      <if test="record.price != null" >
        price = #{record.price,jdbcType=BIGINT},
      </if>
      <if test="record.num != null" >
        num = #{record.num,jdbcType=INTEGER},
      </if>
      <if test="record.barcode != null" >
        barcode = #{record.barcode,jdbcType=VARCHAR},
      </if>
      <if test="record.image != null" >
        image = #{record.image,jdbcType=VARCHAR},
      </if>
      <if test="record.cid != null" >
        cid = #{record.cid,jdbcType=BIGINT},
      </if>
      <if test="record.status != null" >
        status = #{record.status,jdbcType=TINYINT},
      </if>
      <if test="record.created != null" >
        created = #{record.created,jdbcType=TIMESTAMP},
      </if>
      <if test="record.updated != null" >
        updated = #{record.updated,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update tb_item
    set id = #{record.id,jdbcType=BIGINT},
      title = #{record.title,jdbcType=VARCHAR},
      sell_point = #{record.sellPoint,jdbcType=VARCHAR},
      price = #{record.price,jdbcType=BIGINT},
      num = #{record.num,jdbcType=INTEGER},
      barcode = #{record.barcode,jdbcType=VARCHAR},
      image = #{record.image,jdbcType=VARCHAR},
      cid = #{record.cid,jdbcType=BIGINT},
      status = #{record.status,jdbcType=TINYINT},
      created = #{record.created,jdbcType=TIMESTAMP},
      updated = #{record.updated,jdbcType=TIMESTAMP}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.bjsxt.ego.rpc.pojo.TbItem" >
    update tb_item
    <set >
      <if test="title != null" >
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="sellPoint != null" >
        sell_point = #{sellPoint,jdbcType=VARCHAR},
      </if>
      <if test="price != null" >
        price = #{price,jdbcType=BIGINT},
      </if>
      <if test="num != null" >
        num = #{num,jdbcType=INTEGER},
      </if>
      <if test="barcode != null" >
        barcode = #{barcode,jdbcType=VARCHAR},
      </if>
      <if test="image != null" >
        image = #{image,jdbcType=VARCHAR},
      </if>
      <if test="cid != null" >
        cid = #{cid,jdbcType=BIGINT},
      </if>
      <if test="status != null" >
        status = #{status,jdbcType=TINYINT},
      </if>
      <if test="created != null" >
        created = #{created,jdbcType=TIMESTAMP},
      </if>
      <if test="updated != null" >
        updated = #{updated,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.bjsxt.ego.rpc.pojo.TbItem" >
    update tb_item
    set title = #{title,jdbcType=VARCHAR},
      sell_point = #{sellPoint,jdbcType=VARCHAR},
      price = #{price,jdbcType=BIGINT},
      num = #{num,jdbcType=INTEGER},
      barcode = #{barcode,jdbcType=VARCHAR},
      image = #{image,jdbcType=VARCHAR},
      cid = #{cid,jdbcType=BIGINT},
      status = #{status,jdbcType=TINYINT},
      created = #{created,jdbcType=TIMESTAMP},
      updated = #{updated,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=BIGINT}
  </update>
</mapper>
View Code

相关文章:

  • 2021-10-19
  • 2021-12-30
  • 2021-11-13
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-08
  • 2021-09-15
相关资源
相似解决方案