MyBatis Generator的使用

31 篇文章 1 订阅
12 篇文章 0 订阅

什么是MyBatis Generator

MyBatis Generator(MBG)是MyBatis MyBatis 和iBATIS的代码生成器。它将为所有版本的MyBatis以及版本2.2.0之后的iBATIS版本生成代码。它将内省数据库表(或许多表),并将生成可用于访问表的工件。这减少了设置对象和配置文件以与数据库表交互的初始麻烦。MBG寻求对简单CRUD(创建,检索,更新,删除)的大部分数据库操作产生重大影响。您仍然需要为连接查询或存储过程手动编写SQL和对象代码。


Mybatis

简单来说,mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具,它可以极大地减少我们对代码的编写,增加我们的开发效率。

在这里使用Maven插件来使用MyBatis Generator

一、在Maven中配置MyBatis Generator插件

  1. 在pom.xml中导入MyBatis Generator的依赖
    <build>
    	<pluginManagement>
    	</pluginManagement>
    	
    	<plugins>
      
        		<plugin>
          			<groupId>org.mybatis.generator</groupId>
          			<artifactId>mybatis-generator-maven-plugin</artifactId>
          			<version>1.3.2</version>
          			<configuration>
            			<verbose>true</verbose>
            			<overwrite>true</overwrite>
          			</configuration>
        		</plugin>
    
    			<!-- geelynote maven的核心插件之-complier插件默认只支持编译Java 1.4,因此需要加上支持高版本jre的配置,在pom.xml里面加上 增加编译插件 -->
      			<plugin>
        			<groupId>org.apache.maven.plugins</groupId>
        			<artifactId>maven-compiler-plugin</artifactId>
        			<version>2.3.2</version>
        			<configuration>
          				<source>1.7</source>
          				<target>1.7</target>
          				<encoding>UTF-8</encoding>
          				<compilerArguments>
            				<extdirs>${project.basedir}/src/main/webapp/WEB-INF/lib</extdirs>
          				</compilerArguments>
        			</configuration>
      			</plugin>
        
      		</plugins>
    </build>
    
    plugins标签与pluginManagement标签处于同一级

  1. 创建generatorConfig.xml文件对MyBatis Generator插件进行配置
    <?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="datasource.properties"></properties>
    
    	<!--指定特定数据库的jdbc驱动jar包的位置-->
    	<classPathEntry location="${db.driverLocation}"/>
    
    	<context id="default" targetRuntime="MyBatis3">
    
        	<!-- optional,旨在创建class时,对注释进行控制 -->
        	<commentGenerator>
            	<property name="suppressDate" value="true"/>
            	<property name="suppressAllComments" value="true"/>
        	</commentGenerator>
    
        	<!--jdbc的数据库连接 -->
        	<jdbcConnection
                driverClass="${db.driverClassName}"
                connectionURL="${db.url}"
                userId="${db.username}"
                password="${db.password}">
        	</jdbcConnection>
    
    
        	<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
        	<javaTypeResolver>
            	<property name="forceBigDecimals" value="false"/>
        	</javaTypeResolver>
    
    
        	<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
            	targetPackage     指定生成的model生成所在的包名
            	targetProject     指定在该项目下所在的路径
        	-->
        	<!--<javaModelGenerator targetPackage="com.mmall.pojo" targetProject=".\src\main\java">-->
        	<javaModelGenerator targetPackage="com.mmall.pojo" targetProject="./src/main/java">
            	<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            	<property name="enableSubPackages" value="false"/>
            	<!-- 是否对model添加 构造函数 -->
            	<property name="constructorBased" value="true"/>
            	<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
            	<property name="trimStrings" value="true"/>
            	<!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            	<property name="immutable" value="false"/>
        	</javaModelGenerator>
    
        	<!--mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->
        	<!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
        	<sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            	<property name="enableSubPackages" value="false"/>
        	</sqlMapGenerator>
    
        	<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
                type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
                type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
                type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
        	-->
    
        	<!-- targetPackage:mapper接口dao生成的位置 -->
        	<!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject=".\src\main\java">-->
        	<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject="./src/main/java">
            	<!-- enableSubPackages:是否让schema作为包的后缀 -->
            	<property name="enableSubPackages" value="false" />
        	</javaClientGenerator>
    
    
        	<table tableName="mmall_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        	<table tableName="mmall_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        	<table tableName="mmall_cart_item" domainObjectName="CartItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        	<table tableName="mmall_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        	<table tableName="mmall_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        	<table tableName="mmall_order_item" domainObjectName="OrderItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
            <table tableName="mmall_pay_info" domainObjectName="PayInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
        	<table tableName="mmall_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            	<columnOverride column="detail" jdbcType="VARCHAR" />
            	<columnOverride column="sub_images" jdbcType="VARCHAR" />
        	</table>
        	<table tableName="mmall_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    
    
        	<!-- geelynote mybatis插件的搭建 -->
    	</context>
    </generatorConfiguration>
    

  1. 在generatorConfig.xml文件的同一级目录下创建datasource.properties文件配置数据源
    db.driverLocation=D:\\demo\\mmall\\src\\main\\resources\\mysql-connector-java-5.1.6.jar
    db.driverClassName=com.mysql.jdbc.Driver
    
    #db.url=jdbc:mysql://192.1.1.1:3306/mmall?characterEncoding=utf-8
    db.url=jdbc:mysql://localhost:3306/mmall_learning?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;serverTimezone=GMT
    db.username=root
    db.password=root
    
    
    db.initialSize = 20
    db.maxActive = 50
    db.maxIdle = 20
    db.minIdle = 10
    db.maxWait = 10
    db.defaultAutoCommit = true
    db.minEvictableIdleTimeMillis = 3600000
    

  1. 使用Mybatis Generator生成文件
    生成文件


配置中的坑

  1. generatorConfig.xml文件中"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"标红
    解决方案:
    在pom中添加一个依赖:
    <!-- mybatis-generator-core 反向生成java代码-->
    
    <dependency>
    
    <groupId>org.mybatis.generator</groupId>
    
    <artifactId>mybatis-generator-core</artifactId>
    
    <version>1.3.5</version>
    
    </dependency>
    
    LifecycleExecutionException、mybatis-generator-config_1_0.dtd标红:逆向工程常见错误    好命靠努力

  1. 在Maven Projects的插件中根本就找不到mybatis-generator插件,无法运行
    检查pom.xml文件中的build标签中的plugins标签是否与pluginManagement标签处于同一级。如果plugins标签在pluginManagement标签里面,就会导致在Maven Projects找不到mybatis-generator插件

    idea创建Maven项目时Maven插件内看不到mybatis-generator  Hank_YH

    mybatis-generator 的坑我都走了一遍   隔壁赵大壮


  1. ‘build.plugins.plugin.version’ for org.apache.maven.plugins:maven-compiler-plugin is missing. @ line 16, column 12
    修改POM.xml,增加maven-compiler-plugin插件版本信息,如下
    <plugins>    
    	<plugin>
        	<groupId>org.apache.maven.plugins</groupId>
        	<artifactId>maven-compiler-plugin</artifactId>  
        	<version>2.3.2</version>  
        	<configuration>    
            	<source>1.6</source>    
            	<target>1.6</target>    
        	</configuration>    
    	</plugin>    
    </plugins>
    
    maven-compiler-plugin 版本错误解决方法    sylvia.liu

  1. 找不到resource路径
    查看在配置文件中的路径,在Windows下,使用的是\,在Linux环境下,使用的是/,在Windows环境下使用\时要注意\的转义,要用两个\

  1. 更多错误推荐查询:mybatis-generator 的坑我都走了一遍   隔壁赵大壮

  1. 更多配置信息推荐查询:Mybatis Generator最完整配置详解    叩丁狼教育
  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
mybatis也能方向生成代码,能方向生成实体类(po)、mapper接口和Mapper接口映射文件,能减少我们代码的工作量。详细步骤如下 1、下载mybatis生成架包工具MyBatis_Generator_1.3.1.zip,解压架包把features、plugins文件夹下的架包分别拷贝到eclipse安装目录下的features、plugins文件夹。重启eclipse就行。 解压后图片如下: Eclipse路径如图: 拷贝替换如图: 2、创建generatorConfig.xml文件,安装好mybatis 就能创建generatorConfig.xml 3、配置generatorConfig.xml配置文件,详细如下 [html] view plain copy <?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 location="D:\\rep\\mysql\\mysql-connector-java\\5.1.19\\mysql-connector-java-5.1.19.jar" /> --> <classPathEntry location="D:\\repo\\com\\oracle\\ojdbc14\\10.2.0.1.0\\ojdbc14-10.2.0.1.0.jar" /> <context id="DB2Tables" targetRuntime="MyBatis3"> <commentGenerator> <property name="suppressAllComments" value="true" /> <property name="suppressDate" value="true" /> </commentGenerator> <jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@xxx.xxx.xxx.xxx:1521:orcl4" userId="xxx" password="xxxx" /> <javaTypeResolver> <property name="forceBigDecimals" value="false" /> <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal --> </javaTypeResolver> <javaModelGenerator targetPackage="com.pcmall.domain.sale.order" targetProject="pos-service/src/main/java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <sqlMapGenerator targetPackage="mybatis.mapper.sale.order" targetProject="pos-service/src/main/resources"> <property name="enableSubPackages" value="false" /> </sqlMapGenerator> <javaClientGenerator targetPackage="com.pcmall.dao.sale.order" targetProject="pos-service/src/main/java" type="XMLMAPPER"> <property name="enableSubPackages" value="false" /> </javaClientGenerator> <table tableName="hs_zxzflx" enableSelectByExample="false" enableDeleteByExample="false" enableCountByExample="false" selectByExampleQueryId="true" enableUpdateByExample="false"> <!-- <generatedKey column="ID" sqlStatement="oracle" identity="true" /> --> </table> </context> </generatorConfiguration> 4、右击generatorConfig.xml 点击Generate MyBatis/iBATIS Artifacts 生成对应接口、接口映射文件、实体类 5、查看结果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值