最近实现了一个自动生成代码的小demo,记录一下。

1. 原理

  通过表名获取对应的表的字段名字,字段类型以及注释等属性,然后使用freemarker构建模板,将得到的属性注入到模板中,最后生成文件。

2.实现过程

  2.1引入jar包

    Maven pom.xml文件依赖(或者直接从网上下载对应jar包引入项目)

    <dependency>

      <groupId>org.freemarker</groupId>

      <artifactId>freemarker</artifactId>

      <version>2.3.23</version>

    </dependency>

  2.2创建模板(ftl文件)   

  下面是一个实体类的模板,${}为取出传入的值,<#list></#list>为遍历一个集合,<#if></#if>为条件判断,其余语法可以自行在网上了解。

package ${pack}.entity;

public class ${class}Entity{

    /********** 属性 ***********/

<#list properties as property>

    private ${property.javaType} ${property.propertyName};//${property.comment}

</#list>

    /********** 构造函数 ***********/

   public ${class}Entity() {

    }

    public ${class}Entity(<#list properties as property>${property.javaType} ${property.propertyName}<#if property_has_next>, </#if></#list>) {

    <#list properties as property>

        this.${property.propertyName} = ${property.propertyName};

   </#list>

    }

    /********** get/set方法 ***********/

<#list properties as property>

    public ${property.javaType} get${property.propertyName?cap_first}() {

        return ${property.propertyName};

    }

    public void set${property.propertyName?cap_first}(${property.javaType} ${property.propertyName}) {

        this.${property.propertyName} = ${property.propertyName};

    }

</#list>

}

2.3将属性值传入模板并生成文件

/**
* 读取表数据的属性
*/

  List<Property> properties=new ArrayList<>();//实体类集合

 

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dataBase+"?useUnicode=true&characterEncoding=UTF-8",username, password);
DatabaseMetaData dbmd = conn.getMetaData();
rs = dbmd.getColumns(null, null, tableName, null);
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();// 得到结果集列的属性
while (rs.next()) {
Property property=new Property(); //实体类,封装了名称、类型、注释等属性
property.setPropertyName(rs.getString("COLUMN_NAME"));//获取字段名
property.setJavaType(genFieldType(rs.getString("TYPE_NAME")));//获取字段的类型
property.setComment(rs.getString("REMARKS"));//获取字段的备注
properties.add(property);
}

/** 
* 将数据传入模板
*/

//创建Configuration对象
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
//设置模板基本路径
cfg.setDirectoryForTemplateLoading(new File("src/main/resources/template"));
cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_23));
if(properties.size()>0){
//组装数据
Map<String, Object> map = new HashMap<String, Object>();
map.put("class", getClassName(tableName)); //类名
map.put("pack", pack); //包名
map.put("properties", properties);//实体类集合
map.put("tableName", tableName);//表名

//指定模板

Template template=cfg.getTemplate("entity.ftl");

 Writer out = new  OutputStreamWriter(System.out);  

template.process(map, out);//传入数据到模板中

   out.flush();

 File fileDir = new File(“生成文件的文件夹路径”);  

         // 创建文件夹,不存在则创建  

         if(!fileDir.exists()){

             fileDir.mkdirs();

          }

//生成文件

  File output = new File(“生成文件的具体路径”);   

         Writer writer = new FileWriter(output);  

            template.process(map, writer);  

            writer.close();

}

这样就可以根据数据库表生成对应的实体类了,当然也可以创建其他的比如service、dao、controller以及jsp文件等,只需要创建对应的模板传入需要的数据即可。

 

 

posted on 2017-07-27 15:36  fade_faith  阅读(597)  评论(0编辑  收藏  举报