美文网首页
Mybatis自动生成Dao,Bean,Mapper等JAVA代

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

作者: 索隆大大 | 来源:发表于2017-01-10 20:22 被阅读6242次

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

    相关文章

      网友评论

          本文标题:Mybatis自动生成Dao,Bean,Mapper等JAVA代

          本文链接:https://www.haomeiwen.com/subject/mtllbttx.html