MyBatis Generator 简介
MyBatis Generator 连接数据库表并生成MyBatis或iBatis文件。这有助于最大限度地减少使用MyBatis时为数据库文件创建简单CRUD操作所需的工作量。
参考文档:http://www.mybatis.org/generator/
下载地址:https://github.com/mybatis/generator/releases
MyBatis Generator 使用
本例环境已安装java环境,且数据库是mysql,表结构如下:
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
1、使用命令行的方式使用
a、下载mybatis-generator,如下:
、
b、新建配置文件mbg.xml,参考文档:http://www.mybatis.org/generator/
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 -overwrite
d、查看生成目录文件:
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 }
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 }
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 }
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>
2、使用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 }
3、使用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