通過mybatis工具generatorConfig.xml自動生成實體,DAO,映射文件


簡介

  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必須在同一個目錄下。比如我的項目中對應的目錄和文件為:

wKiom1dMHOPC6HJUAABzmYaiyWs263.jpg-wh_50


操作步驟:

1、generatorConfig.xml的基本配置(例子)為:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 <?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、映射文件時會報以下錯誤:

wKioL1dMJgfjiB-MAABULLluWkE177.jpg-wh_50

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、映射文件時可能會報下述錯誤,這個以前在java培訓機構學習的時候,老師特意強調過:

wKiom1dMJOvQ1jbCAAH0UNrHxuM074.jpg-wh_50

3)生成DAO、實體、映射文件的路徑要規范好,我自個的配置同上述generatorConfig.xml的配置,我的項目的基本目錄結構為:

wKiom1dMIIyxOqGVAAA54QpM2ac633.jpg-wh_50

2、執行生成DAO、實體、映射文件的操作。

1)進入到項目對應generatorConfig.xml文件的路徑下。

wKiom1dMHOPC6HJUAABzmYaiyWs263.jpg-wh_50

2)在該目錄按住Shift,右鍵鼠標選擇"在此處打開命令窗口"。

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

wKiom1dMJaGRSNsLAADCzv0-dKU991.jpg-wh_50

一般出現上述圖片中的內容就基本上沒問題。我的項目中對應生成的文件列表為:

wKioL1dMJAiAqUgVAACJ8W3Z4L8103.jpg-wh_50

上述標注藍色勾狀的文件是通過上述命令新生成的

其中新生成的文件內容分別為:

TestMapper 

123456789101112131415161718 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

1234567891011121314151617 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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259 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() {