MyBatis Generator作为maven插件自动生成增删改查代码及布局文件例子

Demo源码

 https://github.com/peterchenhdu/Demos/tree/master/mbgdemo

什么样运作MyBatis Generator

有以下各个运行方式:

个人相比较推荐作为maven插件运行,方便集成,布署。

什么是MyBatis Generator

MyBatis Generator (MBG)
是一个Mybatis的代码生成器,可以自动生成一些简约的CRUD(插入,查询,更新,删除)操作代码,model代码,及mapper配置文件;

怎样布署MyBatis Generator

代码生成器(MBG)是由一个XML配置文件驱动,主要告诉MBG以下三件事

  • 怎样连接到数据库
  • 浮动什么目的,以及如何变化它们
  • 那个表生成靶子

现实怎样布署,可以参考如下链接,已经有很详细的证实了:

http://generator.sturgeon.mopaas.com/configreference/xmlconfig.html

此处给出本Demo的布署,以及相应的注释,如下:

<?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>
<!-- 
MyBatis3Simple     这是默认值  不会有"by example"一类的方法,只有少量的动态SQL。
flat     该模型为每一张表只生成一个实体类。这个实体类包含表中的所有字段
 -->
    <context id="default" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 该插件给实体类添加toString()方法  -->
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        <!-- 这个插件给由MBG生成的Java模型对象增加了equals和hashCode方法 -->
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>

        <!-- 不希望生成的注释中包含时间戳 -->
        <commentGenerator>
            <property name="suppressDate" value="true" />
        </commentGenerator>

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/demo?useUnicode=true&amp;characterEncoding=utf8&amp;zeroDateTimeBehavior=convertToNull"
                        userId="root" password="root">
        </jdbcConnection>

        <!-- 
            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;
         -->
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <javaModelGenerator targetPackage="cn.edu.hdu.mbgdemo.model.generator" targetProject="src/main/java">
             <!-- 是否  自动为每一个生成的类创建一个构造方法-->
            <property name="constructorBased" value="false"/>
            <property name="useActualColumnNames" value="true" />
            <!-- 在targetPackage的基础上,根据数据库的schema再生成一层package-->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否创建一个不可变的类 -->
            <property name="immutable" value="false"/>
            <!-- 设置是否在getter方法中,对String类型字段调用trim()方法 -->
            <property name="trimStrings" value="true"/>
            <property name="rootClass" value="cn.edu.hdu.mbgdemo.base.BaseModel"/>
        </javaModelGenerator>

        <!-- 生成SQL map的XML文件生成器-->
        <sqlMapGenerator targetPackage="mappers.generator" targetProject="src/main/resources">
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <javaClientGenerator targetPackage="cn.edu.hdu.mbgdemo.dao.generator" targetProject="src/main/java" type="XMLMAPPER">
            <property name="enableSubPackages" value="false"/>
            <property name="rootInterface" value="cn.edu.hdu.mbgdemo.base.BaseDao"/>
        </javaClientGenerator>

        <!--这里包含SQL通配符,表示匹配所有demo开头的表-->
        <table tableName="demo_%">

        </table>
    </context>
</generatorConfiguration>

骨子里官网有很全的笺注,想要明白更加多安插,最好参考官网。

MyBatis Generator例子

 新建一个maven工程,编写pom.xml文件,如下,紧如若添加mybatis-generator-maven-plugin插件:

<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>cn.edu.hdu.mbgdemo</groupId>
    <artifactId>mbgdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>mbgdemo</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>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>${project.name}</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
            </resource>
        </resources>
        <pluginManagement>
            <plugins>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.3</version>
                    <configuration>
                        <source>1.7</source>
                        <target>1.7</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>

                <!--帮助开发者让他们的代码兼容下一版本的Java,,Java 9开始,内部API将变为不可访问-->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-jdeps-plugin</artifactId>
                    <version>3.0.0</version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>jdkinternals</goal><!--检查主代码中是否包含对内部API的引用-->
                                <goal>test-jdkinternals</goal><!--检查测试代码中是否包含对内部API的引用-->
                            </goals>
                        </execution>
                    </executions>
                </plugin>

                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                        <configurationFile>src/main/resources/generatorConfig-demo.xml</configurationFile>
                    </configuration>
                    <dependencies>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>5.1.30</version>
                        </dependency>
                    </dependencies>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifacts</id>
                            <goals>
                                <goal>generate</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

下一场编写BaseDao和BaseModel,添加一些共性部分的代码用于被子类继承,如下:

public interface BaseDao<T extends BaseModel> {

    List<T> selectAll();

    int delete(String id);

    T select(String id);

    int insert(T record);

    int update(T record);
}

public class BaseModel implements Serializable {
    /**
     * ID
     */
    private String id;
    /**
     * 是否有效
     */
    private Boolean valid;
    /**
     * 由谁创建
     */
    private String createBy;
    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 最后修改者
     */
    private String updateBy;
    /**
     * 最后修改时间
     */
    private Date updateTime;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Boolean getValid() {
        return valid;
    }
    public void setValid(Boolean valid) {
        this.valid = valid;
    }
    public String getCreateBy() {
        return createBy;
    }
    public void setCreateBy(String createBy) {
        this.createBy = createBy;
    }
    public Date getCreateTime() {
        return createTime;
    }
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
    public String getUpdateBy() {
        return updateBy;
    }
    public void setUpdateBy(String updateBy) {
        this.updateBy = updateBy;
    }
    public Date getUpdateTime() {
        return updateTime;
    }
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

}

编制配置文件generatorConfig-demo.xml,前边部分已经交给了,那里就不贴了,按官网来安顿即可。

说到底执行mybatis-generator:generate命令即可;

推行前与履行后,可以发现自动生成了Dao代码,model代码,mapper配置文件:

图片 1            
图片 2

 那里可以看下自动生成的mapper配置文件,如下,可知mbg能够协助我们大大升高开发成效,而且还足以尽量裁减人为不当:

<?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="cn.edu.hdu.mbgdemo.dao.generator.DemoUserMapper" >
  <resultMap id="BaseResultMap" type="cn.edu.hdu.mbgdemo.model.generator.DemoUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="address" property="address" jdbcType="VARCHAR" />
  </resultMap>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    delete from demo_user
    where id = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="cn.edu.hdu.mbgdemo.model.generator.DemoUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    insert into demo_user (id, name, address
      )
    values (#{id,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR}
      )
  </insert>
  <update id="updateByPrimaryKey" parameterType="cn.edu.hdu.mbgdemo.model.generator.DemoUser" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    update demo_user
    set name = #{name,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR}
    where id = #{id,jdbcType=VARCHAR}
  </update>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select id, name, address
    from demo_user
    where id = #{id,jdbcType=VARCHAR}
  </select>
  <select id="selectAll" resultMap="BaseResultMap" >
    <!--
      WARNING - @mbggenerated
      This element is automatically generated by MyBatis Generator, do not modify.
    -->
    select id, name, address
    from demo_user
  </select>
</mapper>

本来,大家也可以团结往dao添加一些办法,然后在mapper配置文件里增进对应的安插信息。

网站地图xml地图