mybatis逆向工程

什么是逆向工程?

就是我们可以根据数据库表,自动生成javabean,mapper接口和其对应的maaper.xml文件。

现有数据库ssm_curd以及相应的表tbl_emp和tbl_dept:

mybatis逆向工程

mybatis逆向工程

项目的基本目录如下:

mybatis逆向工程

 主要的是配置文件,我们看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="testTables" targetRuntime="MyBatis3">
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>
        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/ssm_curd" userId="root"
            password="123456">
        </jdbcConnection>
        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg" 
            userId="yycg"
            password="yycg">
        </jdbcConnection> -->

        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和 
            NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.gong.generate.bean"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
            targetProject=".\conf">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.gong.generate.dao" 
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table tableName="tbl_emp" domainObjectName="Employee" 
        enableCountByExample="false" enableUpdateByExample="false" 
        enableDeleteByExample="false" enableSelectByExample="false" 
        selectByExampleQueryId="false"></table>
        <table tableName="tbl_dept" domainObjectName="Department" 
        enableCountByExample="false" enableUpdateByExample="false" 
        enableDeleteByExample="false" enableSelectByExample="false" 
        selectByExampleQueryId="false"></table>
        
    </context>
</generatorConfiguration>

我们慢慢来看:

<context id="testTables" targetRuntime="MyBatis3">

id为该配置文件里的标识,targetRuntime为MyBatis3。

<commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />
        </commentGenerator>

去掉生成文件中的注释。

<jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost:3306/ssm_curd" userId="root"
            password="123456">
        </jdbcConnection>

数据库连接配置

<!-- targetProject:生成PO类的位置 -->
        <javaModelGenerator targetPackage="com.gong.generate.bean"
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
            <!-- 从数据库返回的值被清理前后的空格 -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

配置POJO:javaModelGenerator ,具体位置:targetProject,具体包:targetPackage

<sqlMapGenerator targetPackage="mapper"
            targetProject=".\conf">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

配置mapper.xml

<javaClientGenerator type="XMLMAPPER"
            targetPackage="com.gong.generate.dao" 
            targetProject=".\src">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>

配置mapper.java也就是接口。

<table tableName="tbl_emp" domainObjectName="Employee" 
        enableCountByExample="false" enableUpdateByExample="false" 
        enableDeleteByExample="false" enableSelectByExample="false" 
        selectByExampleQueryId="false"></table>
        <table tableName="tbl_dept" domainObjectName="Department" 
        enableCountByExample="false" enableUpdateByExample="false" 
        enableDeleteByExample="false" enableSelectByExample="false" 
        selectByExampleQueryId="false"></table>

指定数据库名称以及要生成的POJO的名称。后面的一些属性是为了不生成类似于EmployeeExample.java等example文件。

接下来是运行的java文件:GeneratorSqlmap.java

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 GeneratorSqlmap {

    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        //指定 逆向工程配置文件
        File configFile = new File("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);

    } 
    public static void main(String[] args) throws Exception {
        try {
            GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
            generatorSqlmap.generator();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

}

我们只需要更改为自己配置文件的位置即可,运行它:控制台

mybatis逆向工程

 点击自己的项目,按F5进行刷新:

mybatis逆向工程

我们发现生成了相关的文件,我们看下其中的一些:

Employee.java

package com.gong.generate.bean;

public class Employee {
    private Integer empId;

    private String empName;

    private String gender;

    private String email;

    private Integer dId;

    public Integer getEmpId() {
        return empId;
    }

    public void setEmpId(Integer empId) {
        this.empId = empId;
    }

    public String getEmpName() {
        return empName;
    }

    public void setEmpName(String empName) {
        this.empName = empName == null ? null : empName.trim();
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender == null ? null : gender.trim();
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email == null ? null : email.trim();
    }

    public Integer getdId() {
        return dId;
    }

    public void setdId(Integer dId) {
        this.dId = dId;
    }
}

发现数据库中的下划线命名字段会转换成java中驼峰命名的属性。

EmployeeMapper.java

package com.gong.generate.dao;

import com.gong.generate.bean.Employee;

public interface EmployeeMapper {
    int deleteByPrimaryKey(Integer empId);

    int insert(Employee record);

    int insertSelective(Employee record);

    Employee selectByPrimaryKey(Integer empId);

    int updateByPrimaryKeySelective(Employee record);

    int updateByPrimaryKey(Employee record);
}

提供了一些默认的方法。

EmployeeMapper.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.gong.generate.dao.EmployeeMapper" >
  <resultMap id="BaseResultMap" type="com.gong.generate.bean.Employee" >
    <id column="emp_id" property="empId" jdbcType="INTEGER" />
    <result column="emp_name" property="empName" jdbcType="VARCHAR" />
    <result column="gender" property="gender" jdbcType="CHAR" />
    <result column="email" property="email" jdbcType="VARCHAR" />
    <result column="d_id" property="dId" jdbcType="INTEGER" />
  </resultMap>
  <sql id="Base_Column_List" >
    emp_id, emp_name, gender, email, d_id
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from tbl_emp
    where emp_id = #{empId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tbl_emp
    where emp_id = #{empId,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.gong.generate.bean.Employee" >
    insert into tbl_emp (emp_id, emp_name, gender, 
      email, d_id)
    values (#{empId,jdbcType=INTEGER}, #{empName,jdbcType=VARCHAR}, #{gender,jdbcType=CHAR}, 
      #{email,jdbcType=VARCHAR}, #{dId,jdbcType=INTEGER})
  </insert>
  <insert id="insertSelective" parameterType="com.gong.generate.bean.Employee" >
    insert into tbl_emp
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="empId != null" >
        emp_id,
      </if>
      <if test="empName != null" >
        emp_name,
      </if>
      <if test="gender != null" >
        gender,
      </if>
      <if test="email != null" >
        email,
      </if>
      <if test="dId != null" >
        d_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="empId != null" >
        #{empId,jdbcType=INTEGER},
      </if>
      <if test="empName != null" >
        #{empName,jdbcType=VARCHAR},
      </if>
      <if test="gender != null" >
        #{gender,jdbcType=CHAR},
      </if>
      <if test="email != null" >
        #{email,jdbcType=VARCHAR},
      </if>
      <if test="dId != null" >
        #{dId,jdbcType=INTEGER},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.gong.generate.bean.Employee" >
    update tbl_emp
    <set >
      <if test="empName != null" >
        emp_name = #{empName,jdbcType=VARCHAR},
      </if>
      <if test="gender != null" >
        gender = #{gender,jdbcType=CHAR},
      </if>
      <if test="email != null" >
        email = #{email,jdbcType=VARCHAR},
      </if>
      <if test="dId != null" >
        d_id = #{dId,jdbcType=INTEGER},
      </if>
    </set>
    where emp_id = #{empId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.gong.generate.bean.Employee" >
    update tbl_emp
    set emp_name = #{empName,jdbcType=VARCHAR},
      gender = #{gender,jdbcType=CHAR},
      email = #{email,jdbcType=VARCHAR},
      d_id = #{dId,jdbcType=INTEGER}
    where emp_id = #{empId,jdbcType=INTEGER}
  </update>
</mapper>

对应的mapper.xml文件,至此mybatis逆向工程就完成了。

相关推荐