Mybatis-Generator

本文详细介绍了如何使用MyBatis-Generator进行代码自动生成,包括命令行、Main方法和Maven插件三种方式,以及解决逆向工程中常见问题的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Mybatis-Generator来帮我们自动生成文件。
 

一、使用命令行

1、相关文件
关于Mybatis-Generator的下载可以到这个地址:https://github.com/mybatis/generator/releases
由于我使用的是Mysql数据库,这里需要再准备一个连接mysql数据库的驱动jar包
以下是相关文件截图:
在这里插入图片描述
和Hibernate逆向生成一样,这里也需要一个配置文件:

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.34.jar"/>
    <context id="MysqlTables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <!--阻止生成的注释包含时间戳,默认为false-->
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/hui" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="com.model" targetProject="src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="com.mapping" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.dao" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成对应表及类名-->
        <table tableName="xiaoqiang" domainObjectName="Xiaoqiang" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

需要修改文件配置的地方我都已经把注释标注出来了,这里的相关路径(如数据库驱动包,生成对应的相关文件位置可以自定义)不能带有中文。
上面配置文件中的:

<table tableName="xiaoqiang" domainObjectName="Xiaoqiang" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

tableName和domainObjectName为必选项,分别代表数据库表名和生成的实体类名,其余的可以自定义去选择(一般情况下均为false)。

生成语句:

java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite

2、使用方法
在该目录按住Shift键,右键鼠标选择"在此处打开命令窗口",复制粘贴生成语句命令即可。

看下效果图:
首先这个是我的数据库表
在这里插入图片描述
在这里插入图片描述
生成的相关代码:
Xiaoqiang.java:

package com.model;

public class Xiaoqiang {
    private Integer id;

    private String title;

    private String describe;

    private String content;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title == null ? null : title.trim();
    }

    public String getDescribe() {
        return describe;
    }

    public void setDescribe(String describe) {
        this.describe = describe == null ? null : describe.trim();
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }
}

XiaoqiangMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dao.XiaoqiangMapper">
  <resultMap id="BaseResultMap" type="com.model.Xiaoqiang">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="title" jdbcType="VARCHAR" property="title" />
    <result column="describe" jdbcType="VARCHAR" property="describe" />
    <result column="content" jdbcType="VARCHAR" property="content" />
  </resultMap>
  <sql id="Base_Column_List">
    id, title, describe, content
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from xiaoqiang
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from xiaoqiang
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.model.Xiaoqiang">
    insert into xiaoqiang (id, title, describe, 
      content)
    values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{describe,jdbcType=VARCHAR}, 
      #{content,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.model.Xiaoqiang">
    insert into xiaoqiang
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="title != null">
        title,
      </if>
      <if test="describe != null">
        describe,
      </if>
      <if test="content != null">
        content,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="title != null">
        #{title,jdbcType=VARCHAR},
      </if>
      <if test="describe != null">
        #{describe,jdbcType=VARCHAR},
      </if>
      <if test="content != null">
        #{content,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.model.Xiaoqiang">
    update xiaoqiang
    <set>
      <if test="title != null">
        title = #{title,jdbcType=VARCHAR},
      </if>
      <if test="describe != null">
        describe = #{describe,jdbcType=VARCHAR},
      </if>
      <if test="content != null">
        content = #{content,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.model.Xiaoqiang">
    update xiaoqiang
    set title = #{title,jdbcType=VARCHAR},
      describe = #{describe,jdbcType=VARCHAR},
      content = #{content,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

XiaoqiangMapper.java:

package com.dao;

import com.model.Xiaoqiang;

public interface XiaoqiangMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Xiaoqiang record);

    int insertSelective(Xiaoqiang record);

    Xiaoqiang selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Xiaoqiang record);

    int updateByPrimaryKey(Xiaoqiang record);
}

 

二、通过Main方法执行配置文件。

1.创建本文我们将使用的工程Mybatis3,工程结构图如下:
在这里插入图片描述
2.修改jdbc.properties文件,具体内容如下:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hui
jdbc.username=root
jdbc.password=root

3.修改log4j.properties,具体内容如下:

log4j.rootLogger=debug,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

4.修改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="jdbc.properties" />
    <context id="MysqlTables" targetRuntime="MyBatis3">
        <!-- 生成的pojo,将implements Serializable-->
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>    
        <commentGenerator>
            <!-- 是否去除自动生成的注释 true:是 : false:否 -->
            <property name="suppressAllComments" value="true" />    
        </commentGenerator>
    
        <!-- 数据库链接URL、用户名、密码 -->
        <jdbcConnection driverClass="${jdbc.driverClassName}"
                        connectionURL="${jdbc.url}"
                        userId="${jdbc.username}"
                        password="${jdbc.password}">
        </jdbcConnection>
    
        <!--
        默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer
            true,把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal
        -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
    
        <!--
        生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如./src/main/java,    
        也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generatord-source目录下
        -->
        <!--<javaModelGenerator targetPackage="com.hui.test.pojo" targetProject="MAVEN">-->    
        <javaModelGenerator targetPackage="com.hui.entity" targetProject="./src/main/java">    
            <property name="enableSubPackages" value="true"/>
            <!-- 从数据库返回的值被清理前后的空格  -->
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
    
        <!--对应的mapper.xml文件  -->
        <sqlMapGenerator targetPackage="mappers" targetProject="./src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
    
        <!-- 对应的Mapper接口类文件 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hui.dao" targetProject="./src/main/java">    
            <property name="enableSubPackages" value="true"/>    
        </javaClientGenerator>    
    
    
        <!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 -->    
        <table tableName="xiaoqiang" domainObjectName="Xiaoqiang"    
               enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false"    
               enableSelectByExample="false" selectByExampleQueryId="false" >    
            <property name="useActualColumnNames" value="false"/>    
        </table>    
    </context>    
</generatorConfiguration>

5.修改GenMain.java文件,具体内容如下:

package com.hui.main;

import java.io.File;  
import java.io.IOException;  
import java.sql.SQLException;  
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.exception.InvalidConfigurationException;  
import org.mybatis.generator.exception.XMLParserException;  
import org.mybatis.generator.internal.DefaultShellCallback;  
  
public class GenMain {  
    public static void main(String[] args) {  
        List<String> warnings = new ArrayList<String>();  
        boolean overwrite = true;  
        String genCfg = "/generatorConfig.xml";  
        File configFile = new File(GenMain.class.getResource(genCfg).getFile());  
        ConfigurationParser cp = new ConfigurationParser(warnings);  
        Configuration config = null;  
        try {  
            config = cp.parseConfiguration(configFile);  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (XMLParserException e) {  
            e.printStackTrace();  
        }  
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);  
        MyBatisGenerator myBatisGenerator = null;  
        try {  
            myBatisGenerator = new MyBatisGenerator(config, callback, warnings);  
        } catch (InvalidConfigurationException e) {  
            e.printStackTrace();  
        }  
        try {  
            myBatisGenerator.generate(null);  
        } catch (SQLException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
    }  
}

6.修改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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hui</groupId>
	<artifactId>Mybatis3</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Mybatis Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<dependencies>
        <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.3.1</version>
		</dependency> -->

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.34</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>Mybatis3</finalName>
	</build>
</project>

7.测试方法:
运行main方法,然后刷新工程即可。正常情况下:控制台能够看到如下输出,刷新工程后项目列表也能够看到填充文件的变化。

DEBUG [main] - Retrieving column information for table "xiaoqiang"
DEBUG [main] - Found column "id", data type 4, in table "hui..xiaoqiang"
DEBUG [main] - Found column "title", data type 12, in table "hui..xiaoqiang"
DEBUG [main] - Found column "describe", data type 12, in table "hui..xiaoqiang"
DEBUG [main] - Found column "content", data type 12, in table "hui..xiaoqiang"

在这里插入图片描述
 

三、通过Maven插件运行。

上面我们的工程是通过maven构建的,mybatis generator中也包含了一个可以集成到Maven的插件,具体做法如下:
1.工程可简化至:
在这里插入图片描述
2.修改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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.hui</groupId>
	<artifactId>Mybatis3</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>Mybatis Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<build>  
        <plugins>  
            <plugin>  
                <groupId>org.mybatis.generator</groupId>  
                <artifactId>mybatis-generator-maven-plugin</artifactId>  
                <version>1.3.5</version>  
                <configuration>  
                    <verbose>true</verbose>  
                    <overwrite>true</overwrite>  
                </configuration>  
            </plugin>  
        </plugins>  
    </build>
</project>

3.在默认情况下,mybatis generator的配置文件的名称为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="C:/Users/Administrator/Desktop/mybatis-generator-1.3.5/mysql-connector-java-5.1.34.jar" />
	<context id="MysqlTables" targetRuntime="MyBatis3">
		<!-- 生成的pojo,将implements Serializable -->
		<plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin>
		<commentGenerator>
			<!-- 是否去除自动生成的注释 true:是 : false:否 -->
			<property name="suppressAllComments" value="true" />
		</commentGenerator>

		<!-- 数据库链接URL、用户名、密码 -->
		<jdbcConnection driverClass="com.mysql.jdbc.Driver"
			connectionURL="jdbc:mysql://127.0.0.1:3306/hui" userId="root"
			password="root">
		</jdbcConnection>

		<!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer true,把JDBC DECIMAL 和 
			NUMERIC 类型解析为java.math.BigDecimal -->
		<javaTypeResolver>
			<property name="forceBigDecimals" value="false" />
		</javaTypeResolver>

		<!-- 生成model模型,对应的包路径,以及文件存放路径(targetProject),targetProject可以指定具体的路径,如./src/main/java, 
			也可以使用“MAVEN”来自动生成,这样生成的代码会在target/generatord-source目录下 -->
		<!--<javaModelGenerator targetPackage="com.hui.test.pojo" targetProject="MAVEN"> -->
		<javaModelGenerator targetPackage="com.hui.entity"
			targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
			<!-- 从数据库返回的值被清理前后的空格 -->
			<property name="trimStrings" value="true" />
		</javaModelGenerator>

		<!--对应的mapper.xml文件 -->
		<sqlMapGenerator targetPackage="mappers"
			targetProject="./src/main/resources">
			<property name="enableSubPackages" value="true" />
		</sqlMapGenerator>

		<!-- 对应的Mapper接口类文件 -->
		<javaClientGenerator type="XMLMAPPER"
			targetPackage="com.hui.dao" targetProject="./src/main/java">
			<property name="enableSubPackages" value="true" />
		</javaClientGenerator>

		<!-- 列出要生成代码的所有表,这里配置的是不生成Example文件 -->
		<table tableName="xiaoqiang" domainObjectName="Xiaoqiang"
			enableCountByExample="false" enableUpdateByExample="false"
			enableDeleteByExample="false" enableSelectByExample="false"
			selectByExampleQueryId="false">
			<property name="useActualColumnNames" value="false" />
		</table>
	</context>
</generatorConfiguration>

4.运行方法:
在eclipse中,选择pom.xml文件,击右键选择Run AS——>Maven Build… ——>在Goals框中输入:mybatis-generator:generate

最后,在给出一个小建议:在建表时,字段名称建议用"_"分隔多个单词,比如:AWB_NO、REC_ID…,这样生成的entity,属性名称就会变成漂亮的驼峰命名,即:awbNo、recId
 

四、解决mybatis-generator无法生成除insert外的方法的问题

mybatis框架提供了非常好用的逆向工程插件,但是在使用过程中会有很多问题。
我在使用中就遇到了只生成insert和insertSeletive方法,而不生成其他根据primary key查询更新删除的方法。

解决方案:
1.检查数据库中的表是否有主键,如果没有主键是不会生成类似selectByPrimaryKey之类的方法的。
2.检查generatorConfig.xml配置文件中的table标签是否把这些属性设为了false,默认是true,如果设为了false则无法生成。

enableSelectByPrimaryKey="true"
enableUpdateByPrimaryKey="true"
enableDeleteByPrimaryKey="true"

3.如果使用的mysql驱动是6.x的,那就无法生成,使用5.x版本的就可以生成。(这个比较坑)

参考:
http://www.cnblogs.com/lichenwei/p/4145696.html
http://www.cnblogs.com/wangkeai/p/6934683.html
https://blog.youkuaiyun.com/l_bestcoder/article/details/77529285

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
发出的红包

打赏作者

小强签名设计

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值