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文件,需要一个配置文件,配置数据库的连接,生成代码的位置等信息。






 
    
    
    
    
      
    
    
    
      
      
    
    
    
      
    
    
    
      
    
    
    

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

/**
 * 生成mybaits相关mapper,bean,dao等
 * @author ZWG
 *
 */
public class MybatisGenerateRun {
    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
       List warnings = new ArrayList();
       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方法,生成成功

Mybatis自动生成Dao,Bean,Mapper等JAVA代码_第1张图片
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元素中增加如下信息:


 
    
    
    

注意: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代码)