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>

    <context id="default" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
        
        <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&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull"
                        userId="root" password="root">
        jdbcConnection>
        
        
        <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" />
            
            <property name="enableSubPackages" value="false"/>
            
            <property name="immutable" value="false"/>
            
            <property name="trimStrings" value="true"/>
            <property name="rootClass" value="cn.edu.hdu.mbgdemo.base.BaseModel"/>
        javaModelGenerator>
        
        
        <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>
        
        
        <table tableName="demo_%">
        
        table>
    context>
generatorConfiguration>

其实官网有很全的注释,想要了解更多配置,最好参考官网。

如何运行MyBatis Generator

有以下四种运行方式:

  • 从 命令提示符 使用 XML 配置文件
  • 作为 Ant 任务 使用 XML 配置文件
  • 作为 Maven Plugin
  • 从另一个 Java 程序 使用 XML 配置文件

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

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.0modelVersion>

    <groupId>cn.edu.hdu.mbgdemogroupId>
    <artifactId>mbgdemoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <packaging>jarpackaging>

    <name>mbgdemoname>
    <url>http://maven.apache.orgurl>

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

    <dependencies>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>3.8.1version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.mybatis.generatorgroupId>
            <artifactId>mybatis-generator-coreartifactId>
            <version>1.3.2version>
        dependency>
    dependencies>

    <build>
        <finalName>${project.name}finalName>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
            resource>
        resources>
        <pluginManagement>
            <plugins>
            
                <plugin>
                    <groupId>org.apache.maven.pluginsgroupId>
                    <artifactId>maven-compiler-pluginartifactId>
                    <version>3.3version>
                    <configuration>
                        <source>1.7source>
                        <target>1.7target>
                        <encoding>UTF-8encoding>
                    configuration>
                plugin>
                
                
                <plugin>
                    <groupId>org.apache.maven.pluginsgroupId>
                    <artifactId>maven-jdeps-pluginartifactId>
                    <version>3.0.0version>
                    <executions>
                        <execution>
                            <goals>
                                <goal>jdkinternalsgoal>
                                <goal>test-jdkinternalsgoal>
                            goals>
                        execution>
                    executions>
                plugin>
                
                <plugin>
                    <groupId>org.mybatis.generatorgroupId>
                    <artifactId>mybatis-generator-maven-pluginartifactId>
                    <version>1.3.2version>
                    <configuration>
                        <verbose>trueverbose>
                        <overwrite>trueoverwrite>
                        <configurationFile>src/main/resources/generatorConfig-demo.xmlconfigurationFile>
                    configuration>
                    <dependencies>
                        <dependency>
                            <groupId>mysqlgroupId>
                            <artifactId>mysql-connector-javaartifactId>
                            <version>5.1.30version>
                        dependency>
                    dependencies>
                    <executions>
                        <execution>
                            <id>Generate MyBatis Artifactsid>
                            <goals>
                                <goal>generategoal>
                            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配置文件:

            

 这里可以看下自动生成的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" >
    
    <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" >
    
    delete from demo_user
    where id = #{id,jdbcType=VARCHAR}
  delete>
  <insert id="insert" parameterType="cn.edu.hdu.mbgdemo.model.generator.DemoUser" >
    
    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" >
    
    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" >
    
    select id, name, address
    from demo_user
    where id = #{id,jdbcType=VARCHAR}
  select>
  <select id="selectAll" resultMap="BaseResultMap" >
    
    select id, name, address
    from demo_user
  select>
mapper>

当然,我们也可以自己往dao添加一些方法,然后在mapper配置文件里添加对应的配置信息。

Demo源码

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

你可能感兴趣的:(MyBatis Generator作为maven插件自动生成增删改查代码及配置文件例子)