走前人的路,充实自己(1)

发布于 2015-11-13 / Java / 0条评论 / 1,494浏览

使用 FreeMarker + JdbcTemplate 生成Java Bean
其实就是代码生成
这次我列举一个简单的,生成mysql对应表的Java Bean
1、建表

CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userName` varchar(45) DEFAULT NULL, `birthday` date DEFAULT NULL, `gender` tinyint(2) DEFAULT 1, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2、搭建一个能调用Spring JdbcTemplate的工程
…忽略
3、代码实现生成Java Bean
GenerateDomainFromTable.java

package com.denghb.duanzi.toolkit; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.List; import java.util.Map; import com.denghb.duanzi.tools.StringTools; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import com.denghb.duanzi.domain.TableInfo; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; /** * Hello world! * */ public class GenerateDomainFromTable { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class); String databaseName = "duanzi"; String tableName = "user"; String domainName = StringTools.firstCharToUpperCase(tableName); // 查询对应数据库对应表的字段信息 String sql = "SELECT * FROM information_schema.COLUMNS WHERE table_name = ? AND table_schema = ?;"; List<TableInfo> list = jdbcTemplate.query(sql, BeanPropertyRowMapper.newInstance(TableInfo.class),tableName,databaseName); System.out.println(list.toString()); Configuration config = new Configuration(); try { String path = new File("").getAbsolutePath(); config.setDirectoryForTemplateLoading(new File(path)); config.setObjectWrapper(new DefaultObjectWrapper()); Template template = config.getTemplate("domain.ftl", "UTF-8"); // 创建数据模型 Map<String,Object> root = new HashMap<String,Object>(); root.put("list", list); root.put("domainName", domainName); root.put("isDateType",true);// 实现方式待优化 File file = new File(domainName+".java"); if (!file.exists()) { // System.out.println("file exist"); file.createNewFile(); } Writer out = new BufferedWriter(new FileWriter(file)); template.process(root, out); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TemplateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

TableInfo.java

package com.denghb.duanzi.domain; import com.denghb.duanzi.tools.StringTools; import org.apache.commons.lang.StringUtils; import java.io.Serializable; public class TableInfo implements Serializable { private static final long serialVersionUID = 1L; private String columnName; private String dataType; private String columnComment; // 大写对象名称 private String objectName; public String getColumnName() { return columnName; } public void setColumnName(String columnName) { this.columnName = columnName; } public String getDataType() { return StringTools.databaseTypeToJavaType(dataType); } public void setDataType(String dataType) { this.dataType = dataType; } public String getColumnComment() { return columnComment; } public void setColumnComment(String columnComment) { this.columnComment = columnComment; } public String getObjectName() { return StringTools.firstCharToUpperCase(this.columnName); } public void setObjectName(String objectName) { this.objectName = objectName; } @Override public String toString() { return "TableInfo [columnName=" + columnName + ", dataType=" + dataType + ", columnComment=" + columnComment + "]"; } }

模版
domain.ftl

package com.denghb.duanzi.domain; import java.io.Serializable; <#if isDateType > import java.util.Date; </#if> /** * */ public class ${domainName} implements Serializable { private static final long serialVersionUID = 1L; <#list list as table> /** ${table.columnComment} */ private ${table.dataType} ${table.columnName}; </#list> <#list list as table> public ${table.dataType} get${table.objectName}(){ return ${table.columnName}; } public void set${table.objectName}(${table.dataType} ${table.columnName}){ this.${table.columnName} = ${table.columnName}; } </#list> @Override public String toString(){ return "${domainName} [<#list list as table>${table.columnName}=" + ${table.columnName} +",</#list>]"; } }

StringTools.java

package com.denghb.duanzi.tools; import org.apache.commons.lang.StringUtils; /** * Created by denghb on 15/11/13. */ public class StringTools { /** * 字符串第一个字符转大写 * @param string * @return */ public static String firstCharToUpperCase(String string){ if(StringUtils.isNotBlank(string)){ int length = string.length(); // 获取第一个转大写 String first = string.substring(0,1); first = first.toUpperCase(); // 判断字符长度 if(1 == length){ return first; } String other = string.substring(1, length); return first+other; } return string; } /** * 数据库类型转java类型 * TODO 待完善 * @param dataType * @return */ public static String databaseTypeToJavaType(String dataType) { if (StringUtils.isNotBlank(dataType)) { dataType = dataType.toLowerCase().trim(); if ("varchar".equals(dataType) || "text".equals(dataType) || "string".equals(dataType)) { dataType = "String"; } else if ("int".equals(dataType) || "integer".equals(dataType)) { dataType = "Integer"; } else if ("bigint".equals(dataType) || "long".equals(dataType)) { dataType = "Long"; } else if ("timestamp".equals(dataType) || "datetime".equals(dataType) || "date".equals(dataType)) { dataType = "Date"; } else if ("tinyint".equals(dataType) || "boolean".equals(dataType)) { dataType = "Boolean"; } else { throw new RuntimeException("dataType not find :" + dataType); } return dataType; } return null; } }

运行后结果
User.java

package com.denghb.duanzi.domain; import java.io.Serializable; import java.util.Date; /** * */ public class User implements Serializable { private static final long serialVersionUID = 1L; /** ID */ private Integer id; /** 用户名 */ private String userName; /** 生日 */ private Date birthday; /** 性别 */ private Boolean gender; public Integer getId(){ return id; } public void setId(Integer id){ this.id = id; } public String getUserName(){ return userName; } public void setUserName(String userName){ this.userName = userName; } public Date getBirthday(){ return birthday; } public void setBirthday(Date birthday){ this.birthday = birthday; } public Boolean getGender(){ return gender; } public void setGender(Boolean gender){ this.gender = gender; } @Override public String toString(){ return "User [id=" + id +",userName=" + userName +",birthday=" + birthday +",gender=" + gender +",]"; } }

是不是很简单呢?

:)

评论
站长统计