我们无需手动编写 实体类、DAO、XML 配置文件,只需要使用 MyBatis 提供的一个 Maven 插件就可以自动生成所需的各种文件便能够满足基本的业务需求,如果业务比较复杂只需要修改相关文件即可。
配置插件
在 pom.xml
文件中增加 mybatis-generator-maven-plugin
插件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 <build> <plugins> <plugin> <groupId> org.mybatis.generator</groupId> <artifactId> mybatis-generator-maven-plugin</artifactId> <version> 1.3 .5 </version> <configuration> <configurationFile> ${basedir}/src/ main/resources/ generator/generatorConfig.xml</configurationFile> <overwrite> true</overwrite> <verbose> true</verbose> </configuration> <dependencies> <dependency> <groupId> mysql</groupId> <artifactId> mysql-connector-java</artifactId> <version> ${mysql.version}</version> </dependency> <dependency> <groupId> tk.mybatis</groupId> <artifactId> mapper</artifactId> <version> 3.4 .4 </version> </dependency> </dependencies> </plugin> </plugins> </build>
configurationFile:自动生成所需的配置文件路径
自动生成的配置
在 src/main/resources/generator/
目录下创建 generatorConfig.xml
配置文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 <?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 > <properties resource ="jdbc.properties" /> <context id ="Mysql" targetRuntime ="MyBatis3Simple" defaultModelType ="flat" > <property name ="beginningDelimiter" value ="`" /> <property name ="endingDelimiter" value ="`" /> <plugin type ="tk.mybatis.mapper.generator.MapperPlugin" > <property name ="mappers" value ="com.funtl.utils.MyMapper" /> </plugin > <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.username}" password="${jdbc.password}"> </jdbcConnection > <javaModelGenerator targetPackage ="com.funtl.hello.spring.boot.entity" targetProject ="src/main/java" /> <sqlMapGenerator targetPackage ="mapper" targetProject ="src/main/resources" /> <javaClientGenerator targetPackage="com.funtl.hello.spring.boot.mapper" targetProject="src/main/java" type="XMLMAPPER"/> <table tableName ="%" > <generatedKey column ="id" sqlStatement ="Mysql" identity ="true" /> </table > </context > </generatorConfiguration >
配置数据源
在 src/main/resources
目录下创建 jdbc.properties
数据源配置:
1 2 3 4 5 jdbc.driverClass =com.mysql.jdbc.Driver jdbc.connectionURL =jdbc:mysql://ip:port/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false jdbc.username =root jdbc.password =123456
插件自动生成命令
1 mvn mybatis-generator:generate
成功生成控制台打印的消息,如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 [INFO ] Scanning for projects.. . [INFO ] [INFO ] ------------------------------------------------------------------------ [INFO ] Building hello-spring-boot 0.0.1-SNAPSHOT [INFO ] ------------------------------------------------------------------------ [INFO ] [INFO ] --- mybatis-generator-maven-plugin:1.3.5:generate (default-cli) @ hello-spring-boot --- [INFO ] Connecting to the Database [INFO ] Introspecting table % [INFO ] Generating Record class for table tb_order [INFO ] Generating Mapper Interface for table tb_order [INFO ] Generating SQL Map for table tb_order [INFO ] Generating Record class for table tb_item_cat [INFO ] Generating Mapper Interface for table tb_item_cat [INFO ] Generating SQL Map for table tb_item_cat [INFO ] Generating Record class for table tb_item_desc [INFO ] Generating Mapper Interface for table tb_item_desc [INFO ] Generating SQL Map for table tb_item_desc [INFO ] Generating Record class for table tb_order_shipping [INFO ] Generating Mapper Interface for table tb_order_shipping [INFO ] Generating SQL Map for table tb_order_shipping [INFO ] Generating Record class for table tb_user [INFO ] Generating Mapper Interface for table tb_user [INFO ] Generating SQL Map for table tb_user [INFO ] Generating Record class for table tb_content [INFO ] Generating Mapper Interface for table tb_content [INFO ] Generating SQL Map for table tb_content [INFO ] Generating Record class for table tb_item_param_item [INFO ] Generating Mapper Interface for table tb_item_param_item [INFO ] Generating SQL Map for table tb_item_param_item [INFO ] Generating Record class for table tb_order_item [INFO ] Generating Mapper Interface for table tb_order_item [INFO ] Generating SQL Map for table tb_order_item [INFO ] Generating Record class for table tb_content_category [INFO ] Generating Mapper Interface for table tb_content_category [INFO ] Generating SQL Map for table tb_content_category [INFO ] Generating Record class for table tb_item [INFO ] Generating Mapper Interface for table tb_item [INFO ] Generating SQL Map for table tb_item [INFO ] Generating Record class for table tb_item_param [INFO ] Generating Mapper Interface for table tb_item_param [INFO ] Generating SQL Map for table tb_item_param [INFO ] Saving file TbOrderMapper.xml [INFO ] Saving file TbItemCatMapper.xml [INFO ] Saving file TbItemDescMapper.xml [INFO ] Saving file TbOrderShippingMapper.xml [INFO ] Saving file TbUserMapper.xml [INFO ] Saving file TbContentMapper.xml [INFO ] Saving file TbItemParamItemMapper.xml [INFO ] Saving file TbOrderItemMapper.xml [INFO ] Saving file TbContentCategoryMapper.xml [INFO ] Saving file TbItemMapper.xml [INFO ] Saving file TbItemParamMapper.xml [INFO ] Saving file TbOrder.java [INFO ] Saving file TbOrderMapper.java [INFO ] Saving file TbItemCat.java [INFO ] Saving file TbItemCatMapper.java [INFO ] Saving file TbItemDesc.java [INFO ] Saving file TbItemDescMapper.java [INFO ] Saving file TbOrderShipping.java [INFO ] Saving file TbOrderShippingMapper.java [INFO ] Saving file TbUser.java [INFO ] Saving file TbUserMapper.java [INFO ] Saving file TbContent.java [INFO ] Saving file TbContentMapper.java [INFO ] Saving file TbItemParamItem.java [INFO ] Saving file TbItemParamItemMapper.java [INFO ] Saving file TbOrderItem.java [INFO ] Saving file TbOrderItemMapper.java [INFO ] Saving file TbContentCategory.java [INFO ] Saving file TbContentCategoryMapper.java [INFO ] Saving file TbItem.java [INFO ] Saving file TbItemMapper.java [INFO ] Saving file TbItemParam.java [INFO ] Saving file TbItemParamMapper.java [WARNING ] Column id, specified as an identity column in table tb_order, does not exist in the table. [WARNING ] Column id, specified as an identity column in table tb_item_desc, does not exist in the table. [WARNING ] Column id, specified as an identity column in table tb_order_shipping, does not exist in the table. [INFO ] ------------------------------------------------------------------------ [INFO ] BUILD SUCCESS [INFO ] ------------------------------------------------------------------------ [INFO ] Total time: 2.901 s [INFO ] Finished at: 2018-05-29T01:24:17+08:00 [INFO ] Final Memory: 12M/192M [INFO ] ------------------------------------------------------------------------
完整配置案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 <?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 > resource:配置资源加载地址,使用resource,MBG从classpath开始找,比如com/myproject/generatorConfig.properties url:配置资源加载地质,使用URL的方式,比如file:///C:/myfolder/generatorConfig.properties. 注意,两个属性只能选址一个; 另外,如果使用了mybatis-generator-maven-plugin,那么在pom.xml中定义的properties都可以直接在generatorConfig.xml中使用 <properties resource ="" url ="" /> --> location属性指明加载jar/zip包的全路径 <classPathEntry location ="/Program Files/IBM/SQLLIB/java/db2java.zip" /> --> context:生成一组对象的环境 id:必选,上下文id,用于在生成错误时提示 defaultModelType:指定生成对象的样式 1,conditional:类似hierarchical; 2,flat:所有内容(主键,blob)等全部生成在一个对象中; 3,hierarchical:主键生成一个XXKey对象(key class),Blob等单独生成一个对象,其他简单属性在一个对象中(record class) targetRuntime: 1,MyBatis3:默认的值,生成基于MyBatis3.x以上版本的内容,包括XXXBySample; 2,MyBatis3Simple:类似MyBatis3,只是不生成XXXBySample; introspectedColumnImpl:类全限定名,用于扩展MBG --> <context id ="mysql" defaultModelType ="hierarchical" targetRuntime ="MyBatis3Simple" > 一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 --> <property name ="autoDelimitKeywords" value ="false" /> <property name ="javaFileEncoding" value ="UTF-8" /> <property name ="javaFormatter" value ="org.mybatis.generator.api.dom.DefaultJavaFormatter" /> <property name ="xmlFormatter" value ="org.mybatis.generator.api.dom.DefaultXmlFormatter" /> <property name ="beginningDelimiter" value ="`" /> <property name ="endingDelimiter" value ="`" /> @TODO:是否可以扩展 # MySQL 8.x: com.mysql.cj.jdbc.Driver --> <jdbcConnection driverClass ="com.mysql.jdbc.Driver" connectionURL ="jdbc:mysql:///pss" userId ="root" password ="admin" > </jdbcConnection > 用于处理DB中的类型到Java中的类型,默认使用JavaTypeResolverDefaultImpl; 注意一点,默认会先尝试使用Integer,Long,Short等来对应 DECIMAL和 NUMERIC数据类型; --> <javaTypeResolver type ="org.mybatis.generator.internal.types.JavaTypeResolverDefaultImpl" > true:使用BigDecimal对应DECIMAL和 NUMERIC数据类型 false:默认, scale>0;length>18:使用BigDecimal; scale=0;length[10,18]:使用Long; scale=0;length[5,9]:使用Integer; scale=0;length<5:使用Short; --> <property name ="forceBigDecimals" value ="false" /> </javaTypeResolver > 负责:1,key类(见context的defaultModelType);2,java类;3,查询类 targetPackage:生成的类要放的包,真实的包受enableSubPackages属性控制; targetProject:目标项目,指定一个存在的目录下,生成的内容会放到指定目录中,如果目录不存在,MBG不会自动建目录 --> <javaModelGenerator targetPackage ="com._520it.mybatis.domain" targetProject ="src/main/java" > 自动为每一个生成的类创建一个构造方法,构造方法包含了所有的field;而不是使用setter; --> <property name ="constructorBased" value ="false" /> <property name ="enableSubPackages" value ="true" /> 是否创建一个不可变的类,如果为true, 那么MBG会创建一个没有setter方法的类,取而代之的是类似constructorBased的类 --> <property name ="immutable" value ="false" /> 如果设置了这个根对象,那么生成的keyClass或者recordClass会继承这个类;在Table的rootClass属性中可以覆盖该选项 注意:如果在key class或者record class中有root class相同的属性,MBG就不会重新生成这些属性了,包括: 1,属性名相同,类型相同,有相同的getter/setter方法; --> <property name ="rootClass" value ="com._520it.mybatis.domain.BaseDomain" /> <property name ="trimStrings" value ="true" /> </javaModelGenerator > 注意,在Mybatis3之后,我们可以使用mapper.xml文件+Mapper接口(或者不用mapper接口), 或者只使用Mapper接口+Annotation,所以,如果 javaClientGenerator配置中配置了需要生成XML的话,这个元素就必须配置 targetPackage/targetProject:同javaModelGenerator --> <sqlMapGenerator targetPackage ="com._520it.mybatis.mapper" targetProject ="src/main/resources" > <property name ="enableSubPackages" value ="true" /> </sqlMapGenerator > targetPackage/targetProject:同javaModelGenerator type:选择怎么生成mapper接口(在MyBatis3/MyBatis3Simple下): 1,ANNOTATEDMAPPER:会生成使用Mapper接口+Annotation的方式创建(SQL生成在annotation中),不会生成对应的XML; 2,MIXEDMAPPER:使用混合配置,会生成Mapper接口,并适当添加合适的Annotation,但是XML会生成在XML中; 3,XMLMAPPER:会生成Mapper接口,接口完全依赖XML; 注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER --> <javaClientGenerator targetPackage ="com._520it.mybatis.mapper" type ="ANNOTATEDMAPPER" targetProject ="src/main/java" > <property name ="enableSubPackages" value ="true" /> <property name ="rootInterface" value ="" /> --> </javaClientGenerator > 选择的table会生成一下文件: 1,SQL map文件 2,生成一个主键类; 3,除了BLOB和主键的其他字段的类; 4,包含BLOB的类; 5,一个用户生成动态查询的条件类(selectByExample, deleteByExample),可选; 6,Mapper接口(可选) tableName(必要):要生成对象的表名; 注意:大小写敏感问题。正常情况下,MBG会自动的去识别数据库标识符的大小写敏感度,在一般情况下,MBG会 根据设置的schema,catalog或tablename去查询数据表,按照下面的流程: 1,如果schema,catalog或tablename中有空格,那么设置的是什么格式,就精确的使用指定的大小写格式去查询; 2,否则,如果数据库的标识符使用大写的,那么MBG自动把表名变成大写再查找; 3,否则,如果数据库的标识符使用小写的,那么MBG自动把表名变成小写再查找; 4,否则,使用指定的大小写格式查询; 另外的,如果在创建表的时候,使用的""把数据库对象规定大小写,就算数据库标识符是使用的大写,在这种情况下也会使用给定的大小写来创建表名; 这个时候,请设置delimitIdentifiers="true"即可保留大小写格式; 可选: 1,schema:数据库的schema; 2,catalog:数据库的catalog; 3,alias:为数据表设置的别名,如果设置了alias,那么生成的所有的SELECT SQL语句中,列名会变成:alias_actualColumnName 4,domainObjectName:生成的domain类的名字,如果不设置,直接使用表名作为domain类的名字;可以设置为somepck.domainName,那么会自动把domainName类再放到somepck包里面; 5,enableInsert(默认true):指定是否生成insert语句; 6,enableSelectByPrimaryKey(默认true):指定是否生成按照主键查询对象的语句(就是getById或get); 7,enableSelectByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询语句; 8,enableUpdateByPrimaryKey(默认true):指定是否生成按照主键修改对象的语句(即update); 9,enableDeleteByPrimaryKey(默认true):指定是否生成按照主键删除对象的语句(即delete); 10,enableDeleteByExample(默认true):MyBatis3Simple为false,指定是否生成动态删除语句; 11,enableCountByExample(默认true):MyBatis3Simple为false,指定是否生成动态查询总条数语句(用于分页的总条数查询); 12,enableUpdateByExample(默认true):MyBatis3Simple为false,指定是否生成动态修改语句(只修改对象中不为空的属性); 13,modelType:参考context元素的defaultModelType,相当于覆盖; 14,delimitIdentifiers:参考tableName的解释,注意,默认的delimitIdentifiers是双引号,如果类似MYSQL这样的数据库,使用的是`(反引号,那么还需要设置context的beginningDelimiter和endingDelimiter属性) 15,delimitAllColumns:设置是否所有生成的SQL中的列名都使用标识符引起来。默认为false,delimitIdentifiers参考context的属性 注意,table里面很多参数都是对javaModelGenerator,context等元素的默认属性的一个复写; --> <table tableName ="userinfo" > <property name ="constructorBased" value ="false" /> <property name ="ignoreQualifiersAtRuntime" value ="false" /> <property name ="immutable" value ="false" /> <property name ="modelOnly" value ="false" /> <property name ="rootClass" value ="" /> --> <property name ="rootInterface" value ="" /> --> <property name ="runtimeCatalog" value ="" /> --> <property name ="runtimeSchema" value ="" /> --> <property name ="runtimeTableName" value ="" /> --> 如果选择的runtime是MyBatis3Simple,那么会生成一个SelectAll方法,如果指定了selectAllOrderByClause,那么会在该SQL中添加指定的这个order条件; --> <property name ="selectAllOrderByClause" value ="age desc,username asc" /> <property name ="useActualColumnNames" value ="false" /> 如果设置了该元素,MBG会在生成的<insert > 元素中生成一条正确的<selectKey > 元素,该元素可选 column:主键的列名; sqlStatement:要生成的selectKey语句,有以下可选项: Cloudscape:相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL() DB2 :相当于selectKey的SQL为: VALUES IDENTITY_VAL_LOCAL() DB2_MF :相当于selectKey的SQL为:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1 Derby :相当于selectKey的SQL为:VALUES IDENTITY_VAL_LOCAL() HSQLDB :相当于selectKey的SQL为:CALL IDENTITY() Informix :相当于selectKey的SQL为:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1 MySql :相当于selectKey的SQL为:SELECT LAST_INSERT_ID() SqlServer :相当于selectKey的SQL为:SELECT SCOPE_IDENTITY() SYBASE :相当于selectKey的SQL为:SELECT @@IDENTITY JDBC :相当于在生成的insert元素上添加useGeneratedKeys="true"和keyProperty属性 <generatedKey column ="" sqlStatement ="" /> --> 该元素会在根据表中列名计算对象属性名之前先重命名列名,非常适合用于表中的列都有公用的前缀字符串的时候, 比如列名为:CUST_ID,CUST_NAME,CUST_EMAIL,CUST_ADDRESS等; 那么就可以设置searchString为"^CUST_",并使用空白替换,那么生成的Customer对象中的属性名称就不是 custId,custName等,而是先被替换为ID,NAME,EMAIL,然后变成属性:id,name,email; 注意,MBG是使用java.util.regex.Matcher.replaceAll来替换searchString和replaceString的, 如果使用了columnOverride元素,该属性无效; <columnRenamingRule searchString ="" replaceString ="" /> --> column:要重新设置的列名; 注意,一个table元素中可以有多个columnOverride元素哈~ --> <columnOverride column ="username" > <property name ="property" value ="userName" /> <property name ="javaType" value ="" /> --> <property name ="jdbcType" value ="" /> --> 注意,mybatis中,不会生成到mybatis-config.xml中的typeHandler 只会生成类似:where id = #{id,jdbcType=BIGINT,typeHandler=com._520it.mybatis.MyTypeHandler}的参数描述 <property name ="jdbcType" value ="" /> --> <property name ="delimitedColumnName" value ="" /> --> </columnOverride > column:指定要忽略的列的名字; delimitedColumnName:参考table元素的delimitAllColumns配置,默认为false 注意,一个table元素中可以有多个ignoreColumn元素 <ignoreColumn column ="deptId" delimitedColumnName ="" /> --> </table > </context > </generatorConfiguration >
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !