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

mybatis-gennerator 插件自动生成mybatis所需要的 dao、bean(model)、mapping xml 文件,可以节省很大一部分精力,把更多精力放在业务逻辑上。

 

Mybatis-Generator 下载地址:

https://github.com/mybatis/generator/releases

 

Eclipse 安装 Mybatis-Generator方式

方式1  Maven 配置依赖

The new artifacts are available in Maven central at

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator</artifactId>
    <version>1.3.5</version>
</dependency>

and

<dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.5</version>
</dependency>

 

方式2  Eclipse Marketplace 搜索安装

mybatis-generator-automatically-generates-dao-model-mapping-05

You can install the eclipse feature from the eclipse market place here: https://marketplace.eclipse.org/content/mybatis-generator

 

 

由于我使用的是 MySQL 数据库,这里需要在准备一个连接MySQL 数据库的驱动 jar 包

以下是相关文件截图:

mybatis-generator-automatically-generates-dao-model-mapping-01

 

和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.0.8-bin.jar"/>
    <context id="DB2Tables"    targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <!--数据库链接地址账号密码-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/mymessages?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true" userId="root" password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <!--生成Model类存放位置-->
        <javaModelGenerator targetPackage="lcw.model" targetProject="src">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成映射文件存放位置-->
        <sqlMapGenerator targetPackage="lcw.mapping" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!--生成Dao类存放位置-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="lcw.dao" targetProject="src">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--生成对应表及类名-->
        <table tableName="message" domainObjectName="Messgae" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>

 

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

上面配置文件中的:

<table tableName="message" domainObjectName="Messgae" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

 

tableName 和 domainObjectName为必选项

tableName,代表数据库里的表名,一般为小写

domainObjectName,代表生成的实体类名,一般首字母为大写

其余的可以自定义去选择,一般情况下均为false

 

生成语句文件:

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

 

2、使用方法

首先这个是我的数据库表

mybatis-generator-automatically-generates-dao-model-mapping-02

mybatis-generator-automatically-generates-dao-model-mapping-03 mybatis-generator-automatically-generates-dao-model-mapping-04

 

生成的相关代码:

Message.java

package lcw.model;

public class Messgae {
    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();
    }
}

 

MessgaeMapper.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="lcw.dao.MessgaeMapper" >
  <resultMap id="BaseResultMap" type="lcw.model.Messgae" >
    <id column="id" property="id" jdbcType="INTEGER" />
    <result column="title" property="title" jdbcType="VARCHAR" />
    <result column="describe" property="describe" jdbcType="VARCHAR" />
    <result column="content" property="content" jdbcType="VARCHAR" />
  </resultMap>
  <sql id="Base_Column_List" >
    id, title, describe, content
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    select 
    <include refid="Base_Column_List" />
    from message
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from message
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="lcw.model.Messgae" >
    insert into message (id, title, describe, 
      content)
    values (#{id,jdbcType=INTEGER}, #{title,jdbcType=VARCHAR}, #{describe,jdbcType=VARCHAR}, 
      #{content,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="lcw.model.Messgae" >
    insert into message
    <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="lcw.model.Messgae" >
    update message
    <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="lcw.model.Messgae" >
    update message
    set title = #{title,jdbcType=VARCHAR},
      describe = #{describe,jdbcType=VARCHAR},
      content = #{content,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

 

MessgaeMapper.java

package lcw.dao;

import lcw.model.Messgae;

public interface MessgaeMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Messgae record);

    int insertSelective(Messgae record);

    Messgae selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Messgae record);

    int updateByPrimaryKey(Messgae record);
}

 

错误提示与解决

问题1: 提示警告 

WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

mybatis-generator-automatically-generates-dao-model-mapping-11

解决:MySQL的版本过高导致,MySQL在高版本需要指明是否进行SSL连接

connectionURL="jdbc:mysql://localhost:3306/mytest?useUnicode=true&characterEncoding=utf8&useSSL=true

 

问题2: 提示错误

对实体 "characterEncoding" 的引用必须以 ';' 分隔符结尾

mybatis-generator-automatically-generates-dao-model-mapping-12

解决:在xml的配置文件中要用  &amp;   代替,修改如下:

connectionURL="jdbc:mysql://localhost:3306/mytest?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=true" 

 

 

参考推荐

Spring MVC 详细示例实战

Maven 构建 Spring MVC 项目的简单示例

Maven 搭建 SpringMVC+Spring+MyBatis 框架实战 推荐