Mybatis自动生成Dao,Bean,Mapper等JAVA代码

下载mysql驱动和mybatis-generator相关包

需要下载mysql驱动和mybatis-generator-core包。可以使用gradle或maven等插件下载或直接去官网下载。本文以gradle为例。

在build.gradle中添加依赖

/*mysql驱动*/
compile 'mysql:mysql-connector-java:5.1.34'
/*mybatis 自动生成插件*/
compile 'org.mybatis.generator:mybatis-generator-core:1.3.5'

在项目中增加配置文件:generatorConfig.xml

反向生成java文件,需要一个配置文件,配置数据库的连接,生成代码的位置等信息。

<?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="DB2Tables" targetRuntime="MyBatis3">
    <!-- 定义如何连接目标数据库 -->
    <jdbcConnection driverClass="${jdbc.driverClassName}" connectionURL="${jdbc.url}" 
                    userId="${jdbc.username}" password="${jdbc.password}">
    </jdbcConnection>
    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>
    <!-- 指定生成 Java 模型对象所属的包 -->
    <javaModelGenerator targetPackage="com.ai.emall.bean.gbean" targetProject="src\main\generate">
      <property name="enableSubPackages" value="false" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!-- 指定生成 SQL 映射文件所属的包和的目标项目 -->
    <sqlMapGenerator targetPackage="mybatis.gmapper"  targetProject="src\main\resources">
      <property name="enableSubPackages" value="false" />
    </sqlMapGenerator>
    <!-- 指定目标包和目标项目生成的客户端接口和类 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.ai.emall.dao.gdao"  targetProject="src\main\generate">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>
    <!-- 设置要生成的表名 -->
    <table tableName="product" >
    </table>
    
  </context>
</generatorConfiguration>

创建Main方法,生成相关代码

/**
 * 生成mybaits相关mapper,bean,dao等
 * @author ZWG
 *
 */
public class MybatisGenerateRun {
    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
       List<String> warnings = new ArrayList<String>();
       boolean overwrite = true;
       //加载generatorEmallConfig文件
       File configFile = new File(MybatisGenerateRun.class.getClassLoader().getResource("generatorConfig.xml").getPath());
       //加载数据库信息,例如driverClassName,username,password,url等
       Properties extraProperties = PropertiesLoaderUtils.loadAllProperties("mybatis/mybatis-emall.properties");
       ConfigurationParser cp = new ConfigurationParser(extraProperties, warnings);
       Configuration config = cp.parseConfiguration(configFile);
       DefaultShellCallback callback = new DefaultShellCallback(overwrite);
       MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
       myBatisGenerator.generate(null);
       if(!CollectionUtils.isEmpty(warnings)){
           for (String warn : warnings) {
            System.out.println(warn);
        }
       }
       System.out.println("生成成功!");
    }
}

运行main方法,生成成功

mybatisGenerate.png

自定义生成的注释

通过上面生成的bean文件,每个字段会生成相应的注释,生成的注释如下:

public class Product {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column product.PRODUCT_ID
     *
     * @mbg.generated Tue Jan 10 19:45:10 CST 2017
     */
    private Long productId;

    /**
     * This method was generated by MyBatis Generator.
     * This method returns the value of the database column product.PRODUCT_ID
     *
     * @return the value of product.PRODUCT_ID
     *
     * @mbg.generated Tue Jan 10 19:45:10 CST 2017
     */
    public Long getProductId() {
        return productId;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method sets the value of the database column product.PRODUCT_ID
     *
     * @param productId the value for product.PRODUCT_ID
     *
     * @mbg.generated Tue Jan 10 19:45:10 CST 2017
     */
    public void setProductId(Long productId) {
        this.productId = productId;
    }

}

可以看到这并不是我们想要的注释,如果我们想生成数据库中的注释,可以使用Mybatis提供的CommentGenerator接口,具体步骤如下:

1. 创建自定义注释生成类,需要继承CommentGenerator接口

/**
 * 自定义Mybatis注释  使用数据库中的注释
 * @author ZWG
 *
 */
public class MybatisGeneratorCommon implements CommentGenerator{

    @Override
    public void addConfigurationProperties(Properties properties) {}

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        //判断数据库中该字段注释是否为空
        if(StringUtils.isEmpty(introspectedColumn.getRemarks()))
            return;
        field.addJavaDocLine("/**"+introspectedColumn.getRemarks()+"*/");       
    }

    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {}

    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {}

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable) {}

    @Override
    public void addClassComment(InnerClass innerClass, IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {}

    @Override
    public void addEnumComment(InnerEnum innerEnum, IntrospectedTable introspectedTable) {}

    @Override
    public void addGetterComment(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if(StringUtils.isEmpty(introspectedColumn.getRemarks()))
            return;
        method.addJavaDocLine("/**获取"+introspectedColumn.getRemarks()+"*/");        
    }

    @Override
    public void addSetterComment(Method method, IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if(StringUtils.isEmpty(introspectedColumn.getRemarks()))
            return;
        method.addJavaDocLine("/**设置"+introspectedColumn.getRemarks()+"*/");
    }

    @Override
    public void addGeneralMethodComment(Method method, IntrospectedTable introspectedTable) {}

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {}

    @Override
    public void addComment(XmlElement xmlElement) {}

    @Override
    public void addRootComment(XmlElement rootElement) {}
}

1. 将自定义的注释类添加到配置中。

在上面generatorConfig.xml中的context元素中增加如下信息:

<!-- 自定义注释生成器  MybatisGeneratorCommon类为我自定义的继承CommentGenerator的类 -->
 <commentGenerator type="com.ai.emall.util.MybatisGeneratorCommon">
    <!--  关闭自动生成的注释  -->
    <property name="suppressAllComments" value="true" />
    <property name="suppressDate" value="true" />
</commentGenerator>

注意:generatorConfig.xml中的context下面的元素有严格的顺序关系,上面的commentGenerator需要放到jdbcConnection标签的前面。==
具体顺序为:"(property,plugin,commentGenerator?,(connectionFactory|jdbcConnection),javaTypeResolver?,javaModelGenerator,sqlMapGenerator?,javaClientGenerator?,table +)".

使用自定义注释类,生成的bean文件如下:

public class Product {
    /**产品ID*/
    private Long productId;

    /**获取产品ID*/
    public Long getProductId() {
        return productId;
    }

    /**设置产品ID*/
    public void setProductId(Long productId) {
        this.productId = productId;
    }
}

参考:
generatorConfig.xml完整的配置文件
mybatis-generator 官网
mybatis-generator用户指南

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,010评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,974评论 6 342
  • 最近读的大多是杂文,比起一个晚上就能读完的小说,散文对我来说难读的多,主要是静不下心来。 这段时间回国一直在旅游,...
    雪子呀阅读 293评论 0 2
  • 说实话想把梦里的东西重新回忆起来再加以描写出来确实是一件不容易的事情。我只有一些碎片性的记忆,所以写起来尤为的困难...
    092c1a9b2003阅读 261评论 0 1