【Mybatis】MyBatis之Generator自動生成代碼(九)

MyBatis Generator 簡介

  MyBatis Generator 鏈接數據庫表並生成MyBatis或iBatis文件。這有助於最大限度地減小使用MyBatis時爲數據庫文件建立簡單CRUD操做所需的工做量。java

  參考文檔:http://www.mybatis.org/generator/mysql

  下載地址:https://github.com/mybatis/generator/releasesgit

 

MyBatis Generator 使用

  本例環境已安裝java環境,且數據庫是mysql,表結構以下:github

 1 CREATE DATABASE test_mybatis;  2 USE test_mybatis;  3 
 4 -- ----------------------------
 5 -- Table structure for employee
 6 -- ----------------------------
 7 DROP TABLE IF EXISTS `employee`;  8 CREATE TABLE `employee` (  9   `id` int(11) NOT NULL AUTO_INCREMENT, 10   `last_name` varchar(255) DEFAULT NULL, 11   `gender` char(1) DEFAULT NULL, 12   `email` varchar(255) DEFAULT NULL, 13   `dept_id` int(11) DEFAULT NULL COMMENT '部門ID', 14   PRIMARY KEY (`id`) 15 ) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8; 16 
17 -- ----------------------------
18 -- Records of employee
19 -- ----------------------------
20 BEGIN; 21 INSERT INTO `employee` VALUES (1, '大白', '1', 'dabai@163.com', 1); 22 INSERT INTO `employee` VALUES (2, '小明', '1', 'xiaoming@163.com', 1); 23 INSERT INTO `employee` VALUES (3, '小紅', '1', 'xiaohong@163.com', 1); 24 COMMIT; 25 
26

  一、使用命令行的方式使用sql

    a、下載mybatis-generator,以下:數據庫

      apache

    b、新建配置文件mbg.xml,參考文檔:http://www.mybatis.org/generator/api

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE generatorConfiguration  3  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  4  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
 5 
 6 <generatorConfiguration>
 7 
 8     <classPathEntry  9         location="/Users/h__d/.m2/repository/mysql/mysql-connector-java/8.0.13/mysql-connector-java-8.0.13.jar" />
 10      
 11     <!-- 
 12  context:生成一組對象的環境  13  id:必選,上下文id,用於在生成錯誤時提示  14  defaultModelType:指定生成對象的樣式  15  1,conditional:相似hierarchical;  16  2,flat:全部內容(主鍵,blob)等所有生成在一個對象中;  17  3,hierarchical:主鍵生成一個XXKey對象(key class),Blob等單獨生成一個對象,其餘簡單屬性在一個對象中(record class)  18  targetRuntime:  19  1,MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample;  20  2,MyBatis3Simple:相似MyBatis3,只是不生成XXXBySample;  21  introspectedColumnImpl:類全限定名,用於擴展MBG  22     -->
 23     <context id="DB2Tables" targetRuntime="MyBatis3">
 24     
 25         
 26  
 27         <!-- 自動識別數據庫關鍵字,默認false,若是設置爲true,根據SqlReservedWords中定義的關鍵字列表;  28  通常保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋  29          -->
 30         <property name="autoDelimitKeywords" value="false"/>
 31         <!-- 生成的Java文件的編碼 -->
 32         <property name="javaFileEncoding" value="UTF-8"/>
 33         <!-- 格式化java代碼 -->
 34         <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
 35         <!-- 格式化XML代碼 -->
 36         <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
 37      
 38         <!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,好比ORACLE就是雙引號,MYSQL默認是`反引號; -->
 39         <property name="beginningDelimiter" value="`"/>
 40         <property name="endingDelimiter" value="`"/>
 41         
 42         <!-- 配置pojo的序列化 -->
 43         <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
 44        
 45         <commentGenerator>
 46             <!-- 是否去除自動生成的文檔註釋 true:是 : false:否(默認) -->  
 47             <property name="suppressAllComments" value="true"/> 
 48             <!-- 是否添加數據庫註釋備註 true:是 false:否(默認) -->
 49             <property name="addRemarkComments" value="true" />
 50             <!-- 是否去除自動生成的時間 true:是 : false:否(默認) -->  
 51               <property name="suppressDate" value="false" />
 52               <!-- 註釋時間格式 -->  
 53               <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss" />
 54         </commentGenerator>
 55         
 56         <!-- JDBC 鏈接 -->
 57         <jdbcConnection driverClass="com.mysql.jdbc.Driver"
 58  connectionURL="jdbc:mysql://mysql.naughty7878.top:3306/test_mybatis?allowPublicKeyRetrieval=true"
 59  userId="hd" password="hd123456">
 60         </jdbcConnection>
 61 
 62 
 63         <!-- java類型處理器  64  用於處理DB中的類型到Java中的類型,默認使用JavaTypeResolverDefaultImpl;  65  注意一點,默認會先嚐試使用Integer,Long,Short等來對應DECIMAL和 NUMERIC數據類型;  66          -->
 67         <javaTypeResolver>
 68             <!-- 
 69  true:使用BigDecimal對應DECIMAL和 NUMERIC數據類型  70  false:默認,  71  scale>0;length>18:使用BigDecimal;  72  scale=0;length[10,18]:使用Long;  73  scale=0;length[5,9]:使用Integer;  74  scale=0;length<5:使用Short;  75              -->
 76             <property name="forceBigDecimals" value="false" />
 77         </javaTypeResolver>
 78 
 79         <!-- java模型建立器,是必需要的元素  80  負責:1,key類(見context的defaultModelType);2,java類;3,查詢類  81  targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制;  82  targetProject:目標項目,指定一個存在的目錄下,生成的內容會放到指定目錄中,若是目錄不存在,MBG不會自動建目錄  83         -->
 84         <javaModelGenerator targetPackage="com.test.mybatis.pojo"
 85  targetProject="src/main/java">
 86             
 87             <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
 88             <property name="enableSubPackages" value="true" />
 89             <!-- 設置是否在getter方法中,對String類型字段調用trim()方法 -->
 90             <property name="trimStrings" value="false" />
 91         </javaModelGenerator>
 92 
 93         <!-- 生成SQL map的XML文件生成器,  94  注意,在Mybatis3以後,咱們可使用mapper.xml文件+Mapper接口(或者不用mapper接口),  95  或者只使用Mapper接口+Annotation,因此,若是 javaClientGenerator配置中配置了須要生成XML的話,這個元素就必須配置  96  targetPackage/targetProject:同javaModelGenerator  97         -->
 98         <sqlMapGenerator targetPackage="mapper"
 99  targetProject="src/main/resources">
100             <!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
101             <property name="enableSubPackages" value="true" />
102         </sqlMapGenerator>
103 
104         <!-- 對於mybatis來講,即生成Mapper接口,注意,若是沒有配置該元素,那麼默認不會生成Mapper接口 105  targetPackage/targetProject:同javaModelGenerator 106  type:選擇怎麼生成mapper接口(在MyBatis3/MyBatis3Simple下): 107  1,ANNOTATEDMAPPER:會生成使用Mapper接口+Annotation的方式建立(SQL生成在annotation中),不會生成對應的XML; 108  2,MIXEDMAPPER:使用混合配置,會生成Mapper接口,並適當添加合適的Annotation,可是XML會生成在XML中; 109  3,XMLMAPPER:會生成Mapper接口,接口徹底依賴XML; 110  注意,若是context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER 111         -->
112         <javaClientGenerator type="XMLMAPPER"
113  targetPackage="com.test.mybatis.dao" targetProject="src/main/java">
114             <property name="enableSubPackages" value="true" />
115         </javaClientGenerator>
116 
117 
118         <!-- 選擇一個table來生成相關文件,能夠有一個或多個table,必需要有table元素 119  選擇的table會生成一下文件: 120  1,SQL map文件 121  2,生成一個主鍵類; 122  3,除了BLOB和主鍵的其餘字段的類; 123  4,包含BLOB的類; 124  5,一個用戶生成動態查詢的條件類(selectByExample, deleteByExample),可選; 125  6,Mapper接口(可選) 126  tableName(必要):要生成對象的表名; 127  注意:大小寫敏感問題。正常狀況下,MBG會自動的去識別數據庫標識符的大小寫敏感度,在通常狀況下,MBG會 128  根據設置的schema,catalog或tablename去查詢數據表,按照下面的流程: 129  1,若是schema,catalog或tablename中有空格,那麼設置的是什麼格式,就精確的使用指定的大小寫格式去查詢; 130  2,不然,若是數據庫的標識符使用大寫的,那麼MBG自動把表名變成大寫再查找; 131  3,不然,若是數據庫的標識符使用小寫的,那麼MBG自動把表名變成小寫再查找; 132  4,不然,使用指定的大小寫格式查詢; 133  另外的,若是在建立表的時候,使用的""把數據庫對象規定大小寫,就算數據庫標識符是使用的大寫,在這種狀況下也會使用給定的大小寫來建立表名; 134  這個時候,請設置delimitIdentifiers="true"便可保留大小寫格式; 135  可選: 136  1,schema:數據庫的schema; 137  2,catalog:數據庫的catalog; 138  3,alias:爲數據表設置的別名,若是設置了alias,那麼生成的全部的SELECT SQL語句中,列名會變成:alias_actualColumnName 139  4,domainObjectName:生成的domain類的名字,若是不設置,直接使用表名做爲domain類的名字;能夠設置爲somepck.domainName,那麼會自動把domainName類再放到somepck包裏面; 140  5,enableInsert(默認true):指定是否生成insert語句; 141  6,enableSelectByPrimaryKey(默認true):指定是否生成按照主鍵查詢對象的語句(就是getById或get); 142  7,enableSelectByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢語句; 143  8,enableUpdateByPrimaryKey(默認true):指定是否生成按照主鍵修改對象的語句(即update); 144  9,enableDeleteByPrimaryKey(默認true):指定是否生成按照主鍵刪除對象的語句(即delete); 145  10,enableDeleteByExample(默認true):MyBatis3Simple爲false,指定是否生成動態刪除語句; 146  11,enableCountByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢); 147  12,enableUpdateByExample(默認true):MyBatis3Simple爲false,指定是否生成動態修改語句(只修改對象中不爲空的屬性); 148  13,modelType:參考context元素的defaultModelType,至關於覆蓋; 149  14,delimitIdentifiers:參考tableName的解釋,注意,默認的delimitIdentifiers是雙引號,若是相似MYSQL這樣的數據庫,使用的是`(反引號,那麼還須要設置context的beginningDelimiter和endingDelimiter屬性) 150  15,delimitAllColumns:設置是否全部生成的SQL中的列名都使用標識符引發來。默認爲false,delimitIdentifiers參考context的屬性 151  注意,table裏面不少參數都是對javaModelGenerator,context等元素的默認屬性的一個複寫; 152          -->
153         <table schema="test_mybatis" tableName="employee"
154  domainObjectName="Employee" >
155             <!-- 若是設置爲true,生成的model類會直接使用column自己的名字,而不會再使用駝峯命名方法,好比BORN_DATE,生成的屬性名字就是BORN_DATE,而不會是bornDate -->
156             <property name="useActualColumnNames" value="false" />
157             <!-- generatedKey用於生成生成主鍵的方法, 158  若是設置了該元素,MBG會在生成的<insert>元素中生成一條正確的<selectKey>元素,該元素可選 159  column:主鍵的列名; 160  sqlStatement:要生成的selectKey語句,有如下可選項: 161  Cloudscape:至關於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL() 162  DB2 :至關於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL() 163  DB2_MF :至關於selectKey的SQL爲:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1 164  Derby :至關於selectKey的SQL爲:VALUES IDENTITY_VAL_LOCAL() 165  HSQLDB :至關於selectKey的SQL爲:CALL IDENTITY() 166  Informix :至關於selectKey的SQL爲:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1 167  MySql :至關於selectKey的SQL爲:SELECT LAST_INSERT_ID() 168  SqlServer :至關於selectKey的SQL爲:SELECT SCOPE_IDENTITY() 169  SYBASE :至關於selectKey的SQL爲:SELECT @@IDENTITY 170  JDBC :至關於在生成的insert元素上添加useGeneratedKeys="true"和keyProperty屬性 171             -->
172             <generatedKey column="ID" sqlStatement="MySql"
173  identity="true" />
174             <!-- 用來修改表中某個列的屬性,MBG會使用修改後的列來生成domain的屬性; 175  column:要從新設置的列名; 176  注意,一個table元素中能夠有多個columnOverride元素哈~ 177             -->
178             <columnOverride column="DATE_FIELD"
179  property="startDate" />
180             <!-- ignoreColumn設置一個MGB忽略的列,若是設置了改列,那麼在生成的domain中,生成的SQL中,都不會有該列出現 181  column:指定要忽略的列的名字; 182  delimitedColumnName:參考table元素的delimitAllColumns配置,默認爲false 183  注意,一個table元素中能夠有多個ignoreColumn元素 184             -->
185             <ignoreColumn column="dept_id" />
186             <columnOverride column="gender" jdbcType="VARCHAR" />
187             
188         </table>
189 
190     </context>
191 </generatorConfiguration>

 

    c、使用命令:java -jar mybatis-generator-core-1.3.7.jar -configfile mbg.xml -overwritemybatis

    d、查看生成目錄文件:
app

 1 package com.test.mybatis.pojo;  2 
 3 public class Employee {  4     private Integer id;  5 
 6     private String lastName;  7 
 8     private String gender;  9 
10     private String email; 11 
12     public Integer getId() { 13         return id; 14  } 15 
16     public void setId(Integer id) { 17         this.id = id; 18  } 19 
20     public String getLastName() { 21         return lastName; 22  } 23 
24     public void setLastName(String lastName) { 25         this.lastName = lastName; 26  } 27 
28     public String getGender() { 29         return gender; 30  } 31 
32     public void setGender(String gender) { 33         this.gender = gender; 34  } 35 
36     public String getEmail() { 37         return email; 38  } 39 
40     public void setEmail(String email) { 41         this.email = email; 42  } 43 }
Employee.java
 1 package com.test.mybatis.pojo;  2 
 3 import java.util.ArrayList;  4 import java.util.List;  5 
 6 public class EmployeeExample {  7     protected String orderByClause;  8 
 9     protected boolean distinct;  10 
 11     protected List<Criteria> oredCriteria;  12 
 13     public EmployeeExample() {  14         oredCriteria = new ArrayList<Criteria>();  15  }  16 
 17     public void setOrderByClause(String orderByClause) {  18         this.orderByClause = orderByClause;  19  }  20 
 21     public String getOrderByClause() {  22         return orderByClause;  23  }  24 
 25     public void setDistinct(boolean distinct) {  26         this.distinct = distinct;  27  }  28 
 29     public boolean isDistinct() {  30         return distinct;  31  }  32 
 33     public List<Criteria> getOredCriteria() {  34         return oredCriteria;  35  }  36 
 37     public void or(Criteria criteria) {  38  oredCriteria.add(criteria);  39  }  40 
 41     public Criteria or() {  42         Criteria criteria = createCriteriaInternal();  43  oredCriteria.add(criteria);  44         return criteria;  45  }  46 
 47     public Criteria createCriteria() {  48         Criteria criteria = createCriteriaInternal();  49         if (oredCriteria.size() == 0) {  50  oredCriteria.add(criteria);  51  }  52         return criteria;  53  }  54 
 55     protected Criteria createCriteriaInternal() {  56         Criteria criteria = new Criteria();  57         return criteria;  58  }  59 
 60     public void clear() {  61  oredCriteria.clear();  62         orderByClause = null;  63         distinct = false;  64  }  65 
 66     protected abstract static class GeneratedCriteria {  67         protected List<Criterion> criteria;  68 
 69         protected GeneratedCriteria() {  70             super();  71             criteria = new ArrayList<Criterion>();  72  }  73 
 74         public boolean isValid() {  75             return criteria.size() > 0;  76  }  77 
 78         public List<Criterion> getAllCriteria() {  79             return criteria;  80  }  81 
 82         public List<Criterion> getCriteria() {  83             return criteria;  84  }  85 
 86         protected void addCriterion(String condition) {  87             if (condition == null) {  88                 throw new RuntimeException("Value for condition cannot be null");  89  }  90             criteria.add(new Criterion(condition));  91  }  92 
 93         protected void addCriterion(String condition, Object value, String property) {  94             if (value == null) {  95                 throw new RuntimeException("Value for " + property + " cannot be null");  96  }  97             criteria.add(new Criterion(condition, value));  98  }  99 
100         protected void addCriterion(String condition, Object value1, Object value2, String property) { 101             if (value1 == null || value2 == null) { 102                 throw new RuntimeException("Between values for " + property + " cannot be null"); 103  } 104             criteria.add(new Criterion(condition, value1, value2)); 105  } 106 
107         public Criteria andIdIsNull() { 108             addCriterion("id is null"); 109             return (Criteria) this; 110  } 111 
112         public Criteria andIdIsNotNull() { 113             addCriterion("id is not null"); 114             return (Criteria) this; 115  } 116 
117         public Criteria andIdEqualTo(Integer value) { 118             addCriterion("id =", value, "id"); 119             return (Criteria) this; 120  } 121 
122         public Criteria andIdNotEqualTo(Integer value) { 123             addCriterion("id <>", value, "id"); 124             return (Criteria) this; 125  } 126 
127         public Criteria andIdGreaterThan(Integer value) { 128             addCriterion("id >", value, "id"); 129             return (Criteria) this; 130  } 131 
132         public Criteria andIdGreaterThanOrEqualTo(Integer value) { 133             addCriterion("id >=", value, "id"); 134             return (Criteria) this; 135  } 136 
137         public Criteria andIdLessThan(Integer value) { 138             addCriterion("id <", value, "id"); 139             return (Criteria) this; 140  } 141 
142         public Criteria andIdLessThanOrEqualTo(Integer value) { 143             addCriterion("id <=", value, "id"); 144             return (Criteria) this; 145  } 146 
147         public Criteria andIdIn(List<Integer> values) { 148             addCriterion("id in", values, "id"); 149             return (Criteria) this; 150  } 151 
152         public Criteria andIdNotIn(List<Integer> values) { 153             addCriterion("id not in", values, "id"); 154             return (Criteria) this; 155  } 156 
157         public Criteria andIdBetween(Integer value1, Integer value2) { 158             addCriterion("id between", value1, value2, "id"); 159             return (Criteria) this; 160  } 161 
162         public Criteria andIdNotBetween(Integer value1, Integer value2) { 163             addCriterion("id not between", value1, value2, "id"); 164             return (Criteria) this; 165  } 166 
167         public Criteria andLastNameIsNull() { 168             addCriterion("last_name is null"); 169             return (Criteria) this; 170  } 171 
172         public Criteria andLastNameIsNotNull() { 173             addCriterion("last_name is not null"); 174             return (Criteria) this; 175  } 176 
177         public Criteria andLastNameEqualTo(String value) { 178             addCriterion("last_name =", value, "lastName"); 179             return (Criteria) this; 180  } 181 
182         public Criteria andLastNameNotEqualTo(String value) { 183             addCriterion("last_name <>", value, "lastName"); 184             return (Criteria) this; 185  } 186 
187         public Criteria andLastNameGreaterThan(String value) { 188             addCriterion("last_name >", value, "lastName"); 189             return (Criteria) this; 190  } 191 
192         public Criteria andLastNameGreaterThanOrEqualTo(String value) { 193             addCriterion("last_name >=", value, "lastName"); 194             return (Criteria) this; 195  } 196 
197         public Criteria andLastNameLessThan(String value) { 198             addCriterion("last_name <", value, "lastName"); 199             return (Criteria) this; 200  } 201 
202         public Criteria andLastNameLessThanOrEqualTo(String value) { 203             addCriterion("last_name <=", value, "lastName"); 204             return (Criteria) this; 205  } 206 
207         public Criteria andLastNameLike(String value) { 208             addCriterion("last_name like", value, "lastName"); 209             return (Criteria) this; 210  } 211 
212         public Criteria andLastNameNotLike(String value) { 213             addCriterion("last_name not like", value, "lastName"); 214             return (Criteria) this; 215  } 216 
217         public Criteria andLastNameIn(List<String> values) { 218             addCriterion("last_name in", values, "lastName"); 219             return (Criteria) this; 220  } 221 
222         public Criteria andLastNameNotIn(List<String> values) { 223             addCriterion("last_name not in", values, "lastName"); 224             return (Criteria) this; 225  } 226 
227         public Criteria andLastNameBetween(String value1, String value2) { 228             addCriterion("last_name between", value1, value2, "lastName"); 229             return (Criteria) this; 230  } 231 
232         public Criteria andLastNameNotBetween(String value1, String value2) { 233             addCriterion("last_name not between", value1, value2, "lastName"); 234             return (Criteria) this; 235  } 236 
237         public Criteria andGenderIsNull() { 238             addCriterion("gender is null"); 239             return (Criteria) this; 240  } 241 
242         public Criteria andGenderIsNotNull() { 243             addCriterion("gender is not null"); 244             return (Criteria) this; 245  } 246 
247         public Criteria andGenderEqualTo(String value) { 248             addCriterion("gender =", value, "gender"); 249             return (Criteria) this; 250  } 251 
252         public Criteria andGenderNotEqualTo(String value) { 253             addCriterion("gender <>", value, "gender"); 254             return (Criteria) this; 255  } 256 
257         public Criteria andGenderGreaterThan(String value) { 258             addCriterion("gender >", value, "gender"); 259             return (Criteria) this; 260  } 261 
262         public Criteria andGenderGreaterThanOrEqualTo(String value) { 263             addCriterion("gender >=", value, "gender"); 264             return (Criteria) this; 265  } 266 
267         public Criteria andGenderLessThan(String value) { 268             addCriterion("gender <", value, "gender"); 269             return (Criteria) this; 270  } 271 
272         public Criteria andGenderLessThanOrEqualTo(String value) { 273             addCriterion("gender <=", value, "gender"); 274             return (Criteria) this; 275  } 276 
277         public Criteria andGenderLike(String value) { 278             addCriterion("gender like", value, "gender"); 279             return (Criteria) this; 280  } 281 
282         public Criteria andGenderNotLike(String value) { 283             addCriterion("gender not like", value, "gender"); 284             return (Criteria) this; 285  } 286 
287         public Criteria andGenderIn(List<String> values) { 288             addCriterion("gender in", values, "gender"); 289             return (Criteria) this; 290  } 291 
292         public Criteria andGenderNotIn(List<String> values) { 293             addCriterion("gender not in", values, "gender"); 294             return (Criteria) this; 295  } 296 
297         public Criteria andGenderBetween(String value1, String value2) { 298             addCriterion("gender between", value1, value2, "gender"); 299             return (Criteria) this; 300  } 301 
302         public Criteria andGenderNotBetween(String value1, String value2) { 303             addCriterion("gender not between", value1, value2, "gender"); 304             return (Criteria) this; 305  } 306 
307         public Criteria andEmailIsNull() { 308             addCriterion("email is null"); 309             return (Criteria) this; 310  } 311 
312         public Criteria andEmailIsNotNull() { 313             addCriterion("email is not null"); 314             return (Criteria) this; 315  } 316 
317         public Criteria andEmailEqualTo(String value) { 318             addCriterion("email =", value, "email"); 319             return (Criteria) this; 320  } 321 
322         public Criteria andEmailNotEqualTo(String value) { 323             addCriterion("email <>", value, "email"); 324             return (Criteria) this; 325  } 326 
327         public Criteria andEmailGreaterThan(String value) { 328             addCriterion("email >", value, "email"); 329             return (Criteria) this; 330  } 331 
332         public Criteria andEmailGreaterThanOrEqualTo(String value) { 333             addCriterion("email >=", value, "email"); 334             return (Criteria) this; 335  } 336 
337         public Criteria andEmailLessThan(String value) { 338             addCriterion("email <", value, "email"); 339             return (Criteria) this; 340  } 341 
342         public Criteria andEmailLessThanOrEqualTo(String value) { 343             addCriterion("email <=", value, "email"); 344             return (Criteria) this; 345  } 346 
347         public Criteria andEmailLike(String value) { 348             addCriterion("email like", value, "email"); 349             return (Criteria) this; 350  } 351 
352         public Criteria andEmailNotLike(String value) { 353             addCriterion("email not like", value, "email"); 354             return (Criteria) this; 355  } 356 
357         public Criteria andEmailIn(List<String> values) { 358             addCriterion("email in", values, "email"); 359             return (Criteria) this; 360  } 361 
362         public Criteria andEmailNotIn(List<String> values) { 363             addCriterion("email not in", values, "email"); 364             return (Criteria) this; 365  } 366 
367         public Criteria andEmailBetween(String value1, String value2) { 368             addCriterion("email between", value1, value2, "email"); 369             return (Criteria) this; 370  } 371 
372         public Criteria andEmailNotBetween(String value1, String value2) { 373             addCriterion("email not between", value1, value2, "email"); 374             return (Criteria) this; 375  } 376  } 377 
378     public static class Criteria extends GeneratedCriteria { 379 
380         protected Criteria() { 381             super(); 382  } 383  } 384 
385     public static class Criterion { 386         private String condition; 387 
388         private Object value; 389 
390         private Object secondValue; 391 
392         private boolean noValue; 393 
394         private boolean singleValue; 395 
396         private boolean betweenValue; 397 
398         private boolean listValue; 399 
400         private String typeHandler; 401 
402         public String getCondition() { 403             return condition; 404  } 405 
406         public Object getValue() { 407             return value; 408  } 409 
410         public Object getSecondValue() { 411             return secondValue; 412  } 413 
414         public boolean isNoValue() { 415             return noValue; 416  } 417 
418         public boolean isSingleValue() { 419             return singleValue; 420  } 421 
422         public boolean isBetweenValue() { 423             return betweenValue; 424  } 425 
426         public boolean isListValue() { 427             return listValue; 428  } 429 
430         public String getTypeHandler() { 431             return typeHandler; 432  } 433 
434         protected Criterion(String condition) { 435             super(); 436             this.condition = condition; 437             this.typeHandler = null; 438             this.noValue = true; 439  } 440 
441         protected Criterion(String condition, Object value, String typeHandler) { 442             super(); 443             this.condition = condition; 444             this.value = value; 445             this.typeHandler = typeHandler; 446             if (value instanceof List<?>) { 447                 this.listValue = true; 448             } else { 449                 this.singleValue = true; 450  } 451  } 452 
453         protected Criterion(String condition, Object value) { 454             this(condition, value, null); 455  } 456 
457         protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { 458             super(); 459             this.condition = condition; 460             this.value = value; 461             this.secondValue = secondValue; 462             this.typeHandler = typeHandler; 463             this.betweenValue = true; 464  } 465 
466         protected Criterion(String condition, Object value, Object secondValue) { 467             this(condition, value, secondValue, null); 468  } 469  } 470 }
EmployeeExample.java
 1 package com.test.mybatis.dao;  2 
 3 import com.test.mybatis.pojo.Employee;  4 import com.test.mybatis.pojo.EmployeeExample;  5 import java.util.List;  6 import org.apache.ibatis.annotations.Param;  7 
 8 public interface EmployeeMapper {  9     long countByExample(EmployeeExample example); 10 
11     int deleteByExample(EmployeeExample example); 12 
13     int deleteByPrimaryKey(Integer id); 14 
15     int insert(Employee record); 16 
17     int insertSelective(Employee record); 18 
19     List<Employee> selectByExample(EmployeeExample example); 20 
21  Employee selectByPrimaryKey(Integer id); 22 
23     int updateByExampleSelective(@Param("record") Employee record, @Param("example") EmployeeExample example); 24 
25     int updateByExample(@Param("record") Employee record, @Param("example") EmployeeExample example); 26 
27     int updateByPrimaryKeySelective(Employee record); 28 
29     int updateByPrimaryKey(Employee record); 30 }
EmployeeMapper.java
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 3 <mapper namespace="com.test.mybatis.dao.EmployeeMapper">
 4   <resultMap id="BaseResultMap" type="com.test.mybatis.pojo.Employee">
 5     <id column="id" jdbcType="INTEGER" property="id" />
 6     <result column="last_name" jdbcType="VARCHAR" property="lastName" />
 7     <result column="gender" jdbcType="VARCHAR" property="gender" />
 8     <result column="email" jdbcType="VARCHAR" property="email" />
 9   </resultMap>
 10   <sql id="Example_Where_Clause">
 11     <where>
 12       <foreach collection="oredCriteria" item="criteria" separator="or">
 13         <if test="criteria.valid">
 14           <trim prefix="(" prefixOverrides="and" suffix=")">
 15             <foreach collection="criteria.criteria" item="criterion">
 16               <choose>
 17                 <when test="criterion.noValue">
 18  and ${criterion.condition}  19                 </when>
 20                 <when test="criterion.singleValue">
 21  and ${criterion.condition} #{criterion.value}  22                 </when>
 23                 <when test="criterion.betweenValue">
 24  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  25                 </when>
 26                 <when test="criterion.listValue">
 27  and ${criterion.condition}  28                   <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
 29  #{listItem}  30                   </foreach>
 31                 </when>
 32               </choose>
 33             </foreach>
 34           </trim>
 35         </if>
 36       </foreach>
 37     </where>
 38   </sql>
 39   <sql id="Update_By_Example_Where_Clause">
 40     <where>
 41       <foreach collection="example.oredCriteria" item="criteria" separator="or">
 42         <if test="criteria.valid">
 43           <trim prefix="(" prefixOverrides="and" suffix=")">
 44             <foreach collection="criteria.criteria" item="criterion">
 45               <choose>
 46                 <when test="criterion.noValue">
 47  and ${criterion.condition}  48                 </when>
 49                 <when test="criterion.singleValue">
 50  and ${criterion.condition} #{criterion.value}  51                 </when>
 52                 <when test="criterion.betweenValue">
 53  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}  54                 </when>
 55                 <when test="criterion.listValue">
 56  and ${criterion.condition}  57                   <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
 58  #{listItem}  59                   </foreach>
 60                 </when>
 61               </choose>
 62             </foreach>
 63           </trim>
 64         </if>
 65       </foreach>
 66     </where>
 67   </sql>
 68   <sql id="Base_Column_List">
 69  id, last_name, gender, email  70   </sql>
 71   <select id="selectByExample" parameterType="com.test.mybatis.pojo.EmployeeExample" resultMap="BaseResultMap">
 72  select  73     <if test="distinct">
 74  distinct  75     </if>
 76     <include refid="Base_Column_List" />
 77  from employee  78     <if test="_parameter != null">
 79       <include refid="Example_Where_Clause" />
 80     </if>
 81     <if test="orderByClause != null">
 82  order by ${orderByClause}  83     </if>
 84   </select>
 85   <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
 86  select  87     <include refid="Base_Column_List" />
 88  from employee  89  where id = #{id,jdbcType=INTEGER}  90   </select>
 91   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
 92  delete from employee  93  where id = #{id,jdbcType=INTEGER}  94   </delete>
 95   <delete id="deleteByExample" parameterType="com.test.mybatis.pojo.EmployeeExample">
 96  delete from employee  97     <if test="_parameter != null">
 98       <include refid="Example_Where_Clause" />
 99     </if>
100   </delete>
101   <insert id="insert" parameterType="com.test.mybatis.pojo.Employee">
102     <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
103  SELECT LAST_INSERT_ID() 104     </selectKey>
105  insert into employee (last_name, gender, email 106  ) 107  values (#{lastName,jdbcType=VARCHAR}, #{gender,jdbcType=VARCHAR}, #{email,jdbcType=VARCHAR} 108  ) 109   </insert>
110   <insert id="insertSelective" parameterType="com.test.mybatis.pojo.Employee">
111     <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
112  SELECT LAST_INSERT_ID() 113     </selectKey>
114  insert into employee 115     <trim prefix="(" suffix=")" suffixOverrides=",">
116       <if test="lastName != null">
117  last_name, 118       </if>
119       <if test="gender != null">
120  gender, 121       </if>
122       <if test="email != null">
123  email, 124       </if>
125     </trim>
126     <trim prefix="values (" suffix=")" suffixOverrides=",">
127       <if test="lastName != null">
128  #{lastName,jdbcType=VARCHAR}, 129       </if>
130       <if test="gender != null">
131  #{gender,jdbcType=VARCHAR}, 132       </if>
133       <if test="email != null">
134  #{email,jdbcType=VARCHAR}, 135       </if>
136     </trim>
137   </insert>
138   <select id="countByExample" parameterType="com.test.mybatis.pojo.EmployeeExample" resultType="java.lang.Long">
139  select count(*) from employee 140     <if test="_parameter != null">
141       <include refid="Example_Where_Clause" />
142     </if>
143   </select>
144   <update id="updateByExampleSelective" parameterType="map">
145  update employee 146     <set>
147       <if test="record.id != null">
148  id = #{record.id,jdbcType=INTEGER}, 149       </if>
150       <if test="record.lastName != null">
151  last_name = #{record.lastName,jdbcType=VARCHAR}, 152       </if>
153       <if test="record.gender != null">
154  gender = #{record.gender,jdbcType=VARCHAR}, 155       </if>
156       <if test="record.email != null">
157  email = #{record.email,jdbcType=VARCHAR}, 158       </if>
159     </set>
160     <if test="_parameter != null">
161       <include refid="Update_By_Example_Where_Clause" />
162     </if>
163   </update>
164   <update id="updateByExample" parameterType="map">
165  update employee 166  set id = #{record.id,jdbcType=INTEGER}, 167  last_name = #{record.lastName,jdbcType=VARCHAR}, 168  gender = #{record.gender,jdbcType=VARCHAR}, 169  email = #{record.email,jdbcType=VARCHAR} 170     <if test="_parameter != null">
171       <include refid="Update_By_Example_Where_Clause" />
172     </if>
173   </update>
174   <update id="updateByPrimaryKeySelective" parameterType="com.test.mybatis.pojo.Employee">
175  update employee 176     <set>
177       <if test="lastName != null">
178  last_name = #{lastName,jdbcType=VARCHAR}, 179       </if>
180       <if test="gender != null">
181  gender = #{gender,jdbcType=VARCHAR}, 182       </if>
183       <if test="email != null">
184  email = #{email,jdbcType=VARCHAR}, 185       </if>
186     </set>
187  where id = #{id,jdbcType=INTEGER} 188   </update>
189   <update id="updateByPrimaryKey" parameterType="com.test.mybatis.pojo.Employee">
190  update employee 191  set last_name = #{lastName,jdbcType=VARCHAR}, 192  gender = #{gender,jdbcType=VARCHAR}, 193  email = #{email,jdbcType=VARCHAR} 194  where id = #{id,jdbcType=INTEGER} 195   </update>
196 </mapper>
EmployeeMapper.xml

  二、使用java代碼方式

    a、pom中引入mybatis-generator-core依賴

1 <dependency>
2     <groupId>org.mybatis.generator</groupId>
3     <artifactId>mybatis-generator-core</artifactId>
4     <version>1.3.7</version>
5 </dependency>

    b、代碼

 1 package com.test.mybatis.generator;  2 
 3 import java.io.InputStream;  4 import java.util.ArrayList;  5 import java.util.List;  6 
 7 import org.apache.ibatis.io.Resources;  8 import org.mybatis.generator.api.MyBatisGenerator;  9 import org.mybatis.generator.config.Configuration; 10 import org.mybatis.generator.config.xml.ConfigurationParser; 11 import org.mybatis.generator.internal.DefaultShellCallback; 12 
13 public class TestMBG { 14 
15     public static void main(String[] args) throws Exception { 16         List<String> warnings = new ArrayList<String>(); 17         boolean overwrite = true; 18         // File configFile = new File("mbg.xml");
19         InputStream inputStream = Resources.getResourceAsStream("mbg.xml"); 20 
21         ConfigurationParser cp = new ConfigurationParser(warnings); 22         Configuration config = cp.parseConfiguration(inputStream); 23         DefaultShellCallback callback = new DefaultShellCallback(overwrite); 24         MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings); 25         myBatisGenerator.generate(null); 26  } 27 }

   三、使用maven插件mybatis-generator-plus

    a、pom文件

 1 <build>
 2     <plugins>
 3         <plugin>
 4             <groupId>org.mybatis.generator</groupId>
 5             <artifactId>mybatis-generator-maven-plugin</artifactId>
 6             <version>1.3.7</version>
 7             <dependencies>
 8                 <dependency>
 9                     <groupId>mysql</groupId>
10                     <artifactId>mysql-connector-java</artifactId>
11                     <version>8.0.13</version>
12                 </dependency>
13             </dependencies>
14             <configuration>
15                 <!-- mybatis用於生成代碼的配置文件 -->
16                 <configurationFile>src/main/resources/mbg.xml</configurationFile>
17                 <verbose>true</verbose>
18                 <overwrite>true</overwrite>
19             </configuration>
20         </plugin>
21     </plugins>
22 </build>

    b、mvn命令:mybatis-generator:generate

相關文章
相關標籤/搜索