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用户指南

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,175评论 5 466
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,674评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,151评论 0 328
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,597评论 1 269
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,505评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 47,969评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,455评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,118评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,227评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,213评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,214评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,928评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,512评论 3 302
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,616评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,848评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,228评论 2 344
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,772评论 2 339

推荐阅读更多精彩内容

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