码迷,mamicode.com
首页 > 其他好文 > 详细

通过mybatis工具generatorConfig.xml自动生成实体,DAO,映射文件

时间:2016-05-31 06:38:20      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:mybatis   generatorconfig.xml   

简介

  Mybatis属于半自动ORM,可以利用mybatis工具generatorConfig.xml自动生成DAO、实体、映射文件的方式来代替手动书写的方式,这样既提高了工作效率也可以在项目避免出现的一些细微难调试的BUG。

前提条件:

1、需要准备的第三方jar包为:

mybatis-generator-core-1.3.2.jarmysql-connector-java-5.1.39-bin.jar

其中mybatis-generator-core-1.3.2.jar的下载地址为:

https://github.com/mybatis/generator/releases,

mysql-connector-java-5.1.39-bin.jar的下载地址为:

https://dev.mysql.com/downloads/connector/j/

2、项目自身的generatorConfig.xml文件需要和mybatis-generator-core-1.3.2.jar必须在同一个目录下。比如我的项目中对应的目录和文件为:

技术分享


操作步骤:

1、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>
<!-- classPathEntry:数据库的JDBC驱动的jar包地址--> 
    <classPathEntry location="E:\jar\mysql-connector-java-5.1.39\mysql-connector-java-5.1.39\mysql-connector-java-5.1.39-bin.jar" />
<context id="MysqlTables" targetRuntime="MyBatis3">
<!-- 注释 -->  
<commentGenerator>
<property name="suppressAllComments" value="true"/> <!-- 是否取消注释 --> 
<property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->  
</commentGenerator>
<!-- JDBC连接 -->  
<jdbcConnection driverClass="com.mysql.jdbc.Driver" 
connectionURL="jdbc:mysql://127.0.0.1:3306/jycps?useUnicode=true&amp;characterEncoding=UTF-8"
userId="root"
password="root">
</jdbcConnection>
<!-- 类型转换 -->  
<javaTypeResolver >
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->  
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<!-- 生成实体类地址 -->    
<javaModelGenerator targetPackage="com.jiayou.cps.pojo" targetProject="D:\workspace\jy_cps\jy_cps\src\main\java">
<property name="enableSubPackages" value="true" /> <!-- 是否在当前路径下新加一层-->
<property name="trimStrings" value="true" /> <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
</javaModelGenerator>
<!-- 生成MAPXML文件 -->
<sqlMapGenerator targetPackage="sqlmap/test"  targetProject="D:\workspace\jy_cps\jy_cps\src\main\resources">
<property name="enableSubPackages" value="true" /> <!-- 是否在当前路径下新加一层-->
</sqlMapGenerator>
<!-- 生成DAO -->      
<javaClientGenerator type="XMLMAPPER" targetPackage="com.jiayou.cps.dao"  targetProject="D:\workspace\jy_cps\jy_cps\src\main\java">
<property name="enableSubPackages" value="true" /> <!-- 是否在当前路径下新加一层-->
</javaClientGenerator>
<!-- 配置表信息 -->
<table schema="" tableName="tb_test" domainObjectName="Test" 
   enableCountByExample="true" 
   enableUpdateByExample="true" 
   enableDeleteByExample="true" 
   enableSelectByExample="true" 
   selectByExampleQueryId="true" >
</table>
</context>
</generatorConfiguration>

注意事项:

1)上述配置的XML文件千万不要有注释!暂时在我测试时是这个样子的,可能在执行生成实体、DAO、映射文件时会报以下错误:

技术分享

2)<classPathEntry location="E:\jar\mysql-connector-java-5.1.39\mysql-connector-java-5.1.39\mysql-connector-java-5.1.39-bin.jar" />中的mysql-connector-java-5.1.39-bin.jar版本一定要跟你项目中mysql的jar包版本一致,不然在执行生成实体、DAO、映射文件时可能会报下述错误:

技术分享

3)生成DAO、实体、映射文件的路径要规范好,我自个的配置同上述generatorConfig.xml的配置,我的项目的基本目录结构为:

技术分享

2、执行生成DAO、实体、映射文件的操作。

1)进入到项目对应generatorConfig.xml文件的路径下。

技术分享

2)在该目录按住Shift,右键鼠标选择"在此处打开命令窗口"。

把生成文件的语句“java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite”复制到DOS命令行中,回车等待生成结果。

技术分享

一般出现上述图片中的内容就基本上没问题。我的项目中对应生成的文件列表为:

技术分享

上述标注蓝色勾状的文件是通过上述命令新生成的

其中新生成的文件内容分别为:

TestMapper 

package com.jiayou.cps.dao;
import com.jiayou.cps.pojo.Test;
import com.jiayou.cps.pojo.TestExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface TestMapper {
    int countByExample(TestExample example);
    int deleteByExample(TestExample example);
    int deleteByPrimaryKey(Integer tbId);
    int insert(Test record);
    int insertSelective(Test record);
    List<Test> selectByExample(TestExample example);
    Test selectByPrimaryKey(Integer tbId);
    int updateByExampleSelective(@Param("record") Test record, @Param("example") TestExample example);
    int updateByExample(@Param("record") Test record, @Param("example") TestExample example);
    int updateByPrimaryKeySelective(Test record);
    int updateByPrimaryKey(Test record);
}


Test

package com.jiayou.cps.pojo;
public class Test {
    private Integer tbId;
    private String tbName;
    public Integer getTbId() {
        return tbId;
    }
    public void setTbId(Integer tbId) {
        this.tbId = tbId;
    }
    public String getTbName() {
        return tbName;
    }
    public void setTbName(String tbName) {
        this.tbName = tbName == null ? null : tbName.trim();
    }
}


TestExample

package com.jiayou.cps.pojo;
import java.util.ArrayList;
import java.util.List;
import com.jiayou.cps.mybatis.page.BaseExample;
public class TestExample extends BaseExample{
    protected String orderByClause;
    protected boolean distinct;
    protected List<Criteria> oredCriteria;
    public TestExample() {
        oredCriteria = new ArrayList<Criteria>();
    }
    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }
    public String getOrderByClause() {
        return orderByClause;
    }
    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }
    public boolean isDistinct() {
        return distinct;
    }
    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }
    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }
    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }
    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }
    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }
    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }
    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;
        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }
        public boolean isValid() {
            return criteria.size() > 0;
        }
        public List<Criterion> getAllCriteria() {
            return criteria;
        }
        public List<Criterion> getCriteria() {
            return criteria;
        }
        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }
        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }
        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }
        public Criteria andTbIdIsNull() {
            addCriterion("tb_id is null");
            return (Criteria) this;
        }
        public Criteria andTbIdIsNotNull() {
            addCriterion("tb_id is not null");
            return (Criteria) this;
        }
        public Criteria andTbIdEqualTo(Integer value) {
            addCriterion("tb_id =", value, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdNotEqualTo(Integer value) {
            addCriterion("tb_id <>", value, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdGreaterThan(Integer value) {
            addCriterion("tb_id >", value, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("tb_id >=", value, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdLessThan(Integer value) {
            addCriterion("tb_id <", value, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdLessThanOrEqualTo(Integer value) {
            addCriterion("tb_id <=", value, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdIn(List<Integer> values) {
            addCriterion("tb_id in", values, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdNotIn(List<Integer> values) {
            addCriterion("tb_id not in", values, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdBetween(Integer value1, Integer value2) {
            addCriterion("tb_id between", value1, value2, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbIdNotBetween(Integer value1, Integer value2) {
            addCriterion("tb_id not between", value1, value2, "tbId");
            return (Criteria) this;
        }
        public Criteria andTbNameIsNull() {
            addCriterion("tb_name is null");
            return (Criteria) this;
        }
        public Criteria andTbNameIsNotNull() {
            addCriterion("tb_name is not null");
            return (Criteria) this;
        }
        public Criteria andTbNameEqualTo(String value) {
            addCriterion("tb_name =", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameNotEqualTo(String value) {
            addCriterion("tb_name <>", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameGreaterThan(String value) {
            addCriterion("tb_name >", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameGreaterThanOrEqualTo(String value) {
            addCriterion("tb_name >=", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameLessThan(String value) {
            addCriterion("tb_name <", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameLessThanOrEqualTo(String value) {
            addCriterion("tb_name <=", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameLike(String value) {
            addCriterion("tb_name like", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameNotLike(String value) {
            addCriterion("tb_name not like", value, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameIn(List<String> values) {
            addCriterion("tb_name in", values, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameNotIn(List<String> values) {
            addCriterion("tb_name not in", values, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameBetween(String value1, String value2) {
            addCriterion("tb_name between", value1, value2, "tbName");
            return (Criteria) this;
        }
        public Criteria andTbNameNotBetween(String value1, String value2) {
            addCriterion("tb_name not between", value1, value2, "tbName");
            return (Criteria) this;
        }
    }
    public static class Criteria extends GeneratedCriteria {
        protected Criteria() {
            super();
        }
    }
    public static class Criterion {
        private String condition;
        private Object value;
        private Object secondValue;
        private boolean noValue;
        private boolean singleValue;
        private boolean betweenValue;
        private boolean listValue;
        private String typeHandler;
        public String getCondition() {
            return condition;
        }
        public Object getValue() {
            return value;
        }
        public Object getSecondValue() {
            return secondValue;
        }
        public boolean isNoValue() {
            return noValue;
        }
        public boolean isSingleValue() {
            return singleValue;
        }
        public boolean isBetweenValue() {
            return betweenValue;
        }
        public boolean isListValue() {
            return listValue;
        }
        public String getTypeHandler() {
            return typeHandler;
        }
        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }
        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }
        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }
        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }
        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}

TestMapper.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.jiayou.cps.dao.TestMapper" >
  <resultMap id="BaseResultMap" type="com.jiayou.cps.pojo.Test" >
    <id column="tb_id" property="tbId" jdbcType="INTEGER" />
    <result column="tb_name" property="tbName" 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" >
    tb_id, tb_name
  </sql>
  <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.jiayou.cps.pojo.TestExample" >
    select
    <if test="distinct" >
      distinct
    </if>
    ‘true‘ as QUERYID,
    <include refid="Base_Column_List" />
    from tb_test
    <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 tb_test
    where tb_id = #{tbId,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from tb_test
    where tb_id = #{tbId,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.jiayou.cps.pojo.TestExample" >
    delete from tb_test
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.jiayou.cps.pojo.Test" >
    insert into tb_test (tb_id, tb_name)
    values (#{tbId,jdbcType=INTEGER}, #{tbName,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.jiayou.cps.pojo.Test" >
    insert into tb_test
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="tbId != null" >
        tb_id,
      </if>
      <if test="tbName != null" >
        tb_name,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="tbId != null" >
        #{tbId,jdbcType=INTEGER},
      </if>
      <if test="tbName != null" >
        #{tbName,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.jiayou.cps.pojo.TestExample" resultType="java.lang.Integer" >
    select count(*) from tb_test
    <if test="_parameter != null" >
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map" >
    update tb_test
    <set >
      <if test="record.tbId != null" >
        tb_id = #{record.tbId,jdbcType=INTEGER},
      </if>
      <if test="record.tbName != null" >
        tb_name = #{record.tbName,jdbcType=VARCHAR},
      </if>
    </set>
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map" >
    update tb_test
    set tb_id = #{record.tbId,jdbcType=INTEGER},
      tb_name = #{record.tbName,jdbcType=VARCHAR}
    <if test="_parameter != null" >
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.jiayou.cps.pojo.Test" >
    update tb_test
    <set >
      <if test="tbName != null" >
        tb_name = #{tbName,jdbcType=VARCHAR},
      </if>
    </set>
    where tb_id = #{tbId,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.jiayou.cps.pojo.Test" >
    update tb_test
    set tb_name = #{tbName,jdbcType=VARCHAR}
    where tb_id = #{tbId,jdbcType=INTEGER}
  </update>
</mapper>


本文出自 “你可以选择不平凡” 博客,请务必保留此出处http://ylcodes01.blog.51cto.com/5607366/1784583

通过mybatis工具generatorConfig.xml自动生成实体,DAO,映射文件

标签:mybatis   generatorconfig.xml   

原文地址:http://ylcodes01.blog.51cto.com/5607366/1784583

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!