MyBatis Generator生成代码的几种方式

由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生成器自动生成实体类、DAO接口和Mapper映射文件。这样可以省去一部分的功夫,下面将介绍几种生成方式:

MyBatis Generator 参考文档:

http://blog.csdn.net/isea533/article/details/42102297  

http://www.mybatis.org/generator/running/running.html


第一种:使用命令行创建

生成代码需要的文件和jar包:

         

其中有mybatis框架的jar包,数据库驱动程序jar包以及MyBatis生成器jar包。其中的generatorConfig.xml是需要我们来配置的文件,配置如下:

<?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="mysql-connector-java-5.1.7-bin.jar"/> 
	
	<!-- 	
	jdbc.driver=com.mysql.jdbc.Driver
	url=jdbc:mysql:///test
	username=root
	password=123456 
	-->

  <context id="DB2Tables" targetRuntime="MyBatis3">
  	<!-- 注释 -->  
    <commentGenerator >  
        <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
        <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
    </commentGenerator>
  
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql:///test"
        userId="root"
        password="123456">
    </jdbcConnection>
	
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>



	<!-- 修改包名字 -->
    <javaModelGenerator targetPackage="com.solin.entity" targetProject="../src">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="com.solin.mapper"  targetProject="../src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper"  targetProject="../src">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>
    
    
	 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->    
     <table tableName="user" 
     	domainObjectName="User" 
     	enableCountByExample="false" 
     	enableUpdateByExample="false" 
     	enableDeleteByExample="false" 
     	enableSelectByExample="false" 
     	selectByExampleQueryId="false">
	 </table>
  </context>
  
</generatorConfiguration>
当以上这些完成之后,只需要打开控制台,进入lib目录下,执行脚本:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite即可。

这样在生成之后,就可以在src目录下找到相应的文件夹,每张表都会对应三个文件(实体类、接口、配置文件)

最后附上完整demo:http://download.csdn.net/download/qq_32786873/10020288


第二种:通过MybatisGenerator类和配置文件生成代码

项目结构如下:


generatorConfig.xml配置如下:

<?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="/"/> 
	
	<!-- 	
	jdbc.driver=com.mysql.jdbc.Driver
	url=jdbc:mysql:///test
	username=root
	password=123456 
	-->

  <context id="DB2Tables" targetRuntime="MyBatis3">
  	<!-- 注释 -->  
    <commentGenerator >  
        <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
        <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
    </commentGenerator>
  
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql:///test"
        userId="root"
        password="123456">
    </jdbcConnection>
	
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>



	<!-- 修改包名字 -->
    <javaModelGenerator targetPackage="com.solin.entity" targetProject=".\src">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>
    
    
	 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->    
     <table tableName="user" 
     	domainObjectName="User" 
     	enableCountByExample="false" 
     	enableUpdateByExample="false" 
     	enableDeleteByExample="false" 
     	enableSelectByExample="false" 
     	selectByExampleQueryId="false">
	 </table>
  </context>
  
</generatorConfiguration>
创建MybatisGeneratorUtil类:

package com.solin;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MybatisGeneratorUtil {

	public static void main(String[] args) throws Exception {
		   generator();
	}

	private static void generator() throws Exception {
		List<String> warnings = new ArrayList<String>();
		   boolean overwrite = true;
		   File configFile = new File("generatorConfig.xml");
		   ConfigurationParser cp = new ConfigurationParser(warnings);
		   
		   Configuration config = cp.parseConfiguration(configFile);
		   DefaultShellCallback callback = new DefaultShellCallback(overwrite);
		   MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
		   myBatisGenerator.generate(null);
		   
		   System.out.println("代码生成完毕>>>>>>>>>>>>");
	}

}
执行main方法就可以生成代码了,执行后的结果如下:


最后附上完整demo:http://download.csdn.net/download/qq_32786873/10020408



第三种方式 通过GeneratorAntTask类和配置文件生成

项目结构如下:


generatorConfig.xml配置如下:

<?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="/"/> 
	
	<!-- 	
	jdbc.driver=com.mysql.jdbc.Driver
	url=jdbc:mysql:///test
	username=root
	password=root 
	-->

  <context id="DB2Tables" targetRuntime="MyBatis3">
  	<!-- 注释 -->  
    <commentGenerator >  
        <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
        <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
    </commentGenerator>
  
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql:///test"
        userId="root"
        password="root">
    </jdbcConnection>
	
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>



	<!-- 修改包名字 -->
    <javaModelGenerator targetPackage="com.solin.entity" targetProject=".\src">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

    <sqlMapGenerator targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>

    <javaClientGenerator type="XMLMAPPER" targetPackage="com.solin.mapper"  targetProject=".\src">
      <property name="enableSubPackages" value="false" />
    </javaClientGenerator>
    
    
	 <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->    
     <table tableName="user" 
     	domainObjectName="User" 
     	enableCountByExample="false" 
     	enableUpdateByExample="false" 
     	enableDeleteByExample="false" 
     	enableSelectByExample="false" 
     	selectByExampleQueryId="false">
	 </table>
  </context>
  
</generatorConfiguration>

创建GeneratorAntTaskUtil类:

package com.solin;

import org.mybatis.generator.ant.GeneratorAntTask;

public class GeneratorAntTaskUtil {

	public static void main(String[] args) throws Exception {
		   generator();
	}

	private static void generator() throws Exception {
	   GeneratorAntTask task = new GeneratorAntTask();
       task.setConfigfile("generatorConfig.xml");  //(配置文件具体path)
       task.execute();
	   
	   System.out.println("代码生成完毕>>>>>>>>>>>>");
	}

}

执行main方法就可以生成代码了,执行后的结果如下:


最后附上完整demo:http://download.csdn.net/download/qq_32786873/10022347


第四种:基于Maven插件的方式

首先创建一个Maven工程,项目目录如下:


pom.xml文件配置如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.solin</groupId>
  <artifactId>autoGenerate</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>autoGenerate</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
  <build>
		<finalName>autoGenerate</finalName>
		<plugins>  
	        <plugin>
	           <groupId>org.mybatis.generator</groupId>
	           <artifactId>mybatis-generator-maven-plugin</artifactId>
	           <version>1.3.2</version>
	           <executions>
	              <execution>
	                 <id>Generate MyBatis Files</id>
	                 <goals>
	                    <goal>generate</goal>
	                 </goals>
	                 <phase>generate</phase>
	                 <configuration>
	                    <verbose>true</verbose>
	                    <overwrite>true</overwrite>
	                 </configuration>
	              </execution>
	           </executions>
	 
	           <dependencies>
	              <dependency>
	                 <groupId>mysql</groupId>
	                 <artifactId>mysql-connector-java</artifactId>
	                 <version>5.1.38</version>
	              </dependency>
	              <dependency>
	                 <groupId>org.mybatis.generator</groupId>
	           <artifactId>mybatis-generator-core</artifactId>
	                 <version>1.3.5</version>
	              </dependency>
	 
	              <dependency>
	                 <groupId>org.mybatis</groupId>
	                 <artifactId>mybatis</artifactId>
	                 <version>3.4.2</version>
	              </dependency>
	           </dependencies>
	        </plugin> 
	    </plugins>
	</build>
</project>
generatorConfig.xml文件配置如下:

<?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="application.properties"/>

	<!-- 一个数据库一个context -->  
    <context id="MBG" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin" />
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin>
        
        <!-- 注释 -->  
        <commentGenerator >  
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->  
            <property name="suppressDate" value="true" /> <!-- 是否生成注释带时间戳-->  
        </commentGenerator>  
        
        <!-- jdbc连接 -->  
        <jdbcConnection 
        	driverClass="${jdbc.driverClassName}"
            connectionURL="${jdbc.url}" 
            userId="${jdbc.username}" 
            password="${jdbc.password}">
        </jdbcConnection>

 		<!-- 类型转换 -->  
        <javaTypeResolver>  
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->  
            <property name="forceBigDecimals" value="false"/>  
        </javaTypeResolver>  

		<!-- 生成实体类地址 -->   
        <javaModelGenerator targetPackage="${package.entity}" targetProject="src/main/java">
        	<!-- 该属性只对MyBatis3有效,如果true就会使用构造方法入参,如果false就会使用setter方式。默认为false。 -->
            <property name="constructorBased" value="true" />
             <!-- 是否在当前路径下新加一层schema,eg:fase路径cn.ffcs.test.domain", true:cn.ffcs.test.domain".[schemaName] -->  
            <property name="enableSubPackages" value="false" />
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->  
            <property name="trimStrings" value="true" />
        </javaModelGenerator>

		<!-- 生成mapxml文件 -->  
        <sqlMapGenerator targetPackage="${package.mapper}" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

		<!-- 生成mapxml对应client,也就是接口dao -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="${package.mapper}" targetProject="src/main/java">
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!--   选择一个table来生成相关文件,可以有一个或多个table,必须要有table元素
			        选择的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="${tableName}" 
        	enableCountByExample="false" 
        	enableUpdateByExample="false"
            enableDeleteByExample="false" 
            enableSelectByExample="false"
            selectByExampleQueryId="false">
        	<!-- 参考 javaModelGenerator 的 constructorBased属性-->
            <property name="constructorBased" value="true" />
            <!-- 如果设置为true,生成的model类会直接使用column本身的名字,而不会再使用驼峰命名方法,比如BORN_DATE,生成的属性名字就是BORN_DATE,而不会是bornDate -->
            <property name="useActualColumnNames" value="false" />
            <!-- 默认为false,如果设置为true,在生成的SQL中,table名字不会加上catalog或schema; -->
            <property name="ignoreQualifiersAtRuntime" value="false" />
            <!-- 参考 javaModelGenerator 的 immutable 属性 -->
        	<!-- <property name="immutable" value="false"/> -->
        </table>
    </context>
</generatorConfiguration>
对于generatorConfig.xml文件中引入的 application.properties文件,里面主要是数据库连接信息和生成的文件的目录信息,application.properties文件配置如下:

jdbc.url=jdbc:mysql:///test?createDatabaseIfNotExist=true&useUnicode=true&characterEncoding=utf8
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root

package.entity=com.solin.autoGenerate.entity
package.mapper=com.solin.autoGenerate.mapper
#指定要生成代码的表名,如果tableName等于%,则生成全部表的代码
tableName=user
以上文件配置好了之后,在项目上点击右键,如图:

在点击Run Configurations以后,会弹出对话框,在对话框上找到Maven Build,然后右键并且点击new,如下图:

在新出现的界面上填写Name,Base directory,Goals这三个地方,其中Name可以随便写,Base directory是你的工程的路径,Goals这个地方不用变,照着图写,这个是maven插件的命令。至于Maven  Runtime下拉框可以不选,也可以选择自己安装在eclipse外面的那个。


点击Apply,在点击 Run,稍等一会,你可以看到generate执行成功了,如图:


刷新项目,可以看到生成的文件,如图:


最后附上完整demo:http://download.csdn.net/download/qq_32786873/10022351



第五种:通过eclipse mybatis generater代码生成插件自动生成代码

详细说明见:http://blog.csdn.net/qq_32786873/article/details/78226513



  • 2
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
MyBatis Generator是一个用于生成与数据库交互的代码的工具。当使用MyBatis Generator时,可能会遇到一些错误,其中一种常见的错误是"java.lang.StringIndexOutOfBoundsException: String index out of bounds"。 这个错误通常发生在尝试访问一个字符串的下标时,该下标超过了字符串的长度。这种情况可能会发生在MyBatis Generator生成代码中,特别是在生成查询语句时。 要解决这个问题,可以考虑以下几个方面: 1. 检查生成器配置:请确保已正确配置生成器,包括指定正确的数据库连接信息、表名和字段等。如果配置出错,生成代码可能会导致下标超出范围的错误。 2. 检查数据库表结构:确保数据库表的结构与生成器的期望相匹配。如果表结构发生更改,生成器可能无法正确生成查询语句,导致下标超出范围的错误。 3. 检查自定义方法:如果在生成代码时使用了自定义方法或扩展插件,确保这些方法没有导致下标超出范围的错误。可以查看相关代码并进行调试。 4. 更新 MyBatis Generator 版本:如果使用的是较旧的版本,可能会遇到已知的问题和错误。考虑更新到最新版本,以便修复已知的问题。 总之,"java.lang.StringIndexOutOfBoundsException: String index out of bounds"错误可能是由于MyBatis Generator配置、数据库表结构、自定义方法或使用过时版本等原因导致的。根据具体情况进行逐一排查和解决,可以解决这个问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值