DbProvider.java
package com.whty.platform.generate.codegen;
import java.sql.Connection;
/**
* 数据库信息提供者。该抽象类基于JDBC实现了与数据库方言无关的方法,把与数据库方言相关的操作分派给子类实现。
* @author 黄天政
*/
public abstract class DbProvider {
private Connection conn;
private JdbcConfig jdbcConfig;
/**
* 根据数据库连接构造一个数据库信息提供者
* @param conn 数据库连接
*/
public DbProvider(Connection conn) {
super();
this.conn = conn;
}
/**
* 根据jdbc配置模型构造一个数据库信息提供者
* @param jdbcConfig jdbc配置模型
*/
public DbProvider(JdbcConfig jdbcConfig) {
super();
this.jdbcConfig = jdbcConfig;
}
/**
* @return 获取一个数据库连接
*/
protected Connection getConn() {
if(conn==null){
if(jdbcConfig==null){
try {
throw new Exception(this.getClass().getName()+"jdbcConfig和conn不能同时为null");
} catch (Exception e) {
e.printStackTrace();
}
}
conn = JdbcUtil.getConn(jdbcConfig);
}
return conn;
}
}
JdbcUtil.java
package com.whty.platform.generate.codegen;
import java.io.IOException;
import java.io.Reader;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Jdbc操作工具类
* @author 黄天政
*
*/
public class JdbcUtil {
//private static final Log logger = LogFactory.getLog(JdbcUtil.class);
/**
* 从结果集里当前行某一列数据,列号index从1开始
* @param rs
* @param index 列号 从1开始, 如1,2,3....
* @return
* @throws SQLException
*/
public static Object getResultSetValue(ResultSet rs, int index)
throws SQLException
{
Object obj = rs.getObject(index);
if (obj instanceof Blob) {
obj = rs.getBytes(index);
}
else if (obj instanceof Clob) {
obj = clobToString(rs.getClob(index));
}
else if ((obj != null) && (obj.getClass().getName().startsWith("oracle.sql.TIMESTAMP"))) {
obj = rs.getTimestamp(index);
}
else if ((obj != null) && (obj.getClass().getName().startsWith("oracle.sql.DATE"))) {
String metaDataClassName = rs.getMetaData().getColumnClassName(index);
if (("java.sql.Timestamp".equals(metaDataClassName)) || ("oracle.sql.TIMESTAMP".equals(metaDataClassName)))
{
obj = rs.getTimestamp(index);
}
else {
obj = rs.getDate(index);
}
}
else if ((obj != null) && (obj instanceof Date) &&
("java.sql.Timestamp".equals(rs.getMetaData().getColumnClassName(index)))) {
obj = rs.getTimestamp(index);
}
return obj;
}
/**
* 把Oracle的Clob类型转化为String
* @param clob
* @return
*/
public static String clobToString(java.sql.Clob clob){
String str="";
Reader inStream;
try {
inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
//data是读出并需要返回的数据,类型是String
str = new String(c);
inStream.close();
return str;
}catch (SQLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void safelyClose(Connection conn) {
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void safelyClose(PreparedStatement pstmt) {
if(pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void safelyClose(Statement stmt) {
if(stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void safelyClose(ResultSet rs) {
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void safelyClose(ResultSet rs,Statement stmt){
safelyClose(rs);
safelyClose(stmt);
}
public static void safelyClose(ResultSet rs,Statement stmt,Connection conn) {
safelyClose(rs);
safelyClose(stmt);
safelyClose(conn);
}
public static void safelyClose(ResultSet rs,PreparedStatement pstmt,Connection conn) {
safelyClose(rs);
safelyClose(pstmt);
safelyClose(conn);
}
public static void safelyClose(PreparedStatement pstmt, Connection conn) {
safelyClose(pstmt);
safelyClose(conn);
}
public static void safelyClose(Statement stmt, Connection conn) {
safelyClose(stmt);
safelyClose(conn);
}
public static Connection getConn(JdbcConfig jdbcConfig){
String driver = jdbcConfig.getDriver();
String url = jdbcConfig.getUrl();
String user =jdbcConfig.getUser();
String password =jdbcConfig.getPassword();
try {
Class.forName(driver).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
if(con!=null){
//System.out.println("取得jdbc数据连接成功!");
}else{
System.out.println("取得jdbc数据连接失败!"+jdbcConfig);
}
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
}
Exceptions.java
/**
* Copyright (c) 2005-2012 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.whty.platform.generate.codegen;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 关于异常的工具类.
* @author calvin
* @version 2013-01-15
*/
public class Exceptions {
/**
* 将CheckedException转换为UncheckedException.
*/
public static RuntimeException unchecked(Exception e) {
if (e instanceof RuntimeException) {
return (RuntimeException) e;
} else {
return new RuntimeException(e);
}
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Exception e) {
StringWriter stringWriter = new StringWriter();
e.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 判断异常是否由某些底层的异常引起.
*/
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
Throwable cause = ex.getCause();
while (cause != null) {
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
if (causeClass.isInstance(cause)) {
return true;
}
}
cause = cause.getCause();
}
return false;
}
}
FileUtil.java
package com.whty.platform.generate.codegen;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
/**
* 文件操作工具类
*/
public class FileUtil {
/**
* 根据键值获取properties文件的值
* @param key properties键值
* @param filepath properties文件路径
* @return
*/
public static String getPropertiesByKey(String key,String filepath){
Properties po=new Properties();
FileInputStream inStream;
try {
inStream = new FileInputStream("resource/application.properties");
po.load(inStream);
return po.getProperty(key);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 初始化properties文件
* @param key
* @param filepath
* @return
*/
public static Properties initProperties(String filepath){
Properties po=new Properties();
FileInputStream inStream;
try {
inStream = new FileInputStream(filepath);
po.load(inStream);
return po;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
FileUtils.java
/**
* Copyright © 2012-2013 <a href="www.whty.com.cn">whty</a> All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.whty.platform.generate.codegen;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
import org.apache.tools.zip.ZipOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 文件操作工具类 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能
*
* @author 舒海洋
* @version 2013-01-15
*/
public class FileUtils {
private static Logger log = LoggerFactory.getLogger(FileUtils.class);
/**
* 复制单个文件,如果目标文件存在,则不覆盖
*
* @param srcFileName
* 待复制的文件名
* @param descFileName
* 目标文件名
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFile(String srcFileName, String descFileName) {
return FileUtils.copyFileCover(srcFileName, descFileName, false);
}
/**
* 复制单个文件
*
* @param srcFileName
* 待复制的文件名
* @param descFileName
* 目标文件名
* @param coverlay
* 如果目标文件已存在,是否覆盖
* @return 如果复制成功,则返回true,否则返回false
*/
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {
File srcFile = new File(srcFileName);
// 判断源文件是否存在
if (!srcFile.exists()) {
log.debug("复制文件失败,源文件" + srcFileName + "不存在!");
return false;
}
// 判断源文件是否是合法的文件
else if (!srcFile.isFile()) {
log.debug("复制文件失败," + srcFileName + "不是一个文件!");
return false;
}
File descFile = new File(descFileName);
// 判断目标文件是否存在
if (descFile.exists()) {
// 如果目标文件存在,并且允许覆盖
if (coverlay) {
log.debug("目标文件已存在,准备删除!");
if (!FileUtils.delFile(descFileName)) {
log.debug("删除目标文件" + descFileName + "失败!");
return false;
}
} else {
log.debug("复制文件失败,目标文件" + descFileName + "已存在!");
return false;
}
} else {
if (!descFile.getParentFile().exists()) {
// 如果目标文件所在的目录不存在,则创建目录
log.debug("目标文件所在的目录不存在,创建目录!");
// 创建目标文件所在的目录
if (!descFile.getParentFile().mkdirs()) {
log.debug("创建目标文件所在的目录失败!");
return false;
}
}
}
// 准备复制文件
// 读取的位数
int readByte = 0;
InputStream ins = null;
OutputStream outs = null;
try {
// 打开源文件
ins = new FileInputStream(srcFile);
// 打开目标文件的输出流
outs = new FileOutputStream(descFile);
byte[] buf = new byte[1024];
// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕
while ((readByte = ins.read(buf)) != -1) {
// 将读取的字节流写入到输出流
outs.write(buf, 0, readByte);
}
log.debug("复制单个文件" + srcFileName + "到" + descFileName + "成功!");
return true;
} catch (Exception e) {
log.debug("复制文件失败:" + e.getMessage());
return false;
} finally {
// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
if (outs != null) {
try {
outs.close();
} catch (IOException oute) {
oute.printStackTrace();
}
}
if (ins != null) {
try {
ins.close();
} catch (IOException ine) {
ine.printStackTrace();
}
}
}
}
/**
* 复制整个目录的内容,如果目标目录存在,则不覆盖
*
* @param srcDirName
* 源目录名
* @param descDirName
* 目标目录名
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectory(String srcDirName, String descDirName) {
return FileUtils.copyDirectoryCover(srcDirName, descDirName, false);
}
/**
* 复制整个目录的内容
*
* @param srcDirName
* 源目录名
* @param descDirName
* 目标目录名
* @param coverlay
* 如果目标目录存在,是否覆盖
* @return 如果复制成功返回true,否则返回false
*/
public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {
File srcDir = new File(srcDirName);
// 判断源目录是否存在
if (!srcDir.exists()) {
log.debug("复制目录失败,源目录" + srcDirName + "不存在!");
return false;
}
// 判断源目录是否是目录
else if (!srcDir.isDirectory()) {
log.debug("复制目录失败," + srcDirName + "不是一个目录!");
return false;
}
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
String descDirNames = descDirName;
if (!descDirNames.endsWith(File.separator)) {
descDirNames = descDirNames + File.separator;
}
File descDir = new File(descDirNames);
// 如果目标文件夹存在
if (descDir.exists()) {
if (coverlay) {
// 允许覆盖目标目录
log.debug("目标目录已存在,准备删除!");
if (!FileUtils.delFile(descDirNames)) {
log.debug("删除目录" + descDirNames + "失败!");
return false;
}
} else {
log.debug("目标目录复制失败,目标目录" + descDirNames + "已存在!");
return false;
}
} else {
// 创建目标目录
log.debug("目标目录不存在,准备创建!");
if (!descDir.mkdirs()) {
log.debug("创建目标目录失败!");
return false;
}
}
boolean flag = true;
// 列出源目录下的所有文件名和子目录名
File[] files = srcDir.listFiles();
for (int i = 0; i < files.length; i++) {
// 如果是一个单个文件,则直接复制
if (files[i].isFile()) {
flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName());
// 如果拷贝文件失败,则退出循环
if (!flag) {
break;
}
}
// 如果是子目录,则继续复制目录
if (files[i].isDirectory()) {
flag = FileUtils.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName());
// 如果拷贝目录失败,则退出循环
if (!flag) {
break;
}
}
}
if (!flag) {
log.debug("复制目录" + srcDirName + "到" + descDirName + "失败!");
return false;
}
log.debug("复制目录" + srcDirName + "到" + descDirName + "成功!");
return true;
}
/**
*
* 删除文件,可以删除单个文件或文件夹
*
* @param fileName
* 被删除的文件名
* @return 如果删除成功,则返回true,否是返回false
*/
public static boolean delFile(String fileName) {
File file = new File(fileName);
if (!file.exists()) {
log.debug(fileName + "文件不存在!");
return true;
} else {
if (file.isFile()) {
return FileUtils.deleteFile(fileName);
} else {
return FileUtils.deleteDirectory(fileName);
}
}
}
/**
*
* 删除单个文件
*
* @param fileName
* 被删除的文件名
* @return 如果删除成功,则返回true,否则返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
if (file.exists() && file.isFile()) {
if (file.delete()) {
log.debug("删除单个文件" + fileName + "成功!");
return true;
} else {
log.debug("删除单个文件" + fileName + "失败!");
return false;
}
} else {
log.debug(fileName + "文件不存在!");
return true;
}
}
/**
*
* 删除目录及目录下的文件
*
* @param dirName
* 被删除的目录所在的文件路径
* @return 如果目录删除成功,则返回true,否则返回false
*/
public static boolean deleteDirectory(String dirName) {
String dirNames = dirName;
if (!dirNames.endsWith(File.separator)) {
dirNames = dirNames + File.separator;
}
File dirFile = new File(dirNames);
if (!dirFile.exists() || !dirFile.isDirectory()) {
log.debug(dirNames + "目录不存在!");
return true;
}
boolean flag = true;
// 列出全部文件及子目录
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
// 删除子文件
if (files[i].isFile()) {
flag = FileUtils.deleteFile(files[i].getAbsolutePath());
// 如果删除文件失败,则退出循环
if (!flag) {
break;
}
}
// 删除子目录
else if (files[i].isDirectory()) {
flag = FileUtils.deleteDirectory(files[i].getAbsolutePath());
// 如果删除子目录失败,则退出循环
if (!flag) {
break;
}
}
}
if (!flag) {
log.debug("删除目录失败!");
return false;
}
// 删除当前目录
if (dirFile.delete()) {
log.debug("删除目录" + dirName + "成功!");
return true;
} else {
log.debug("删除目录" + dirName + "失败!");
return false;
}
}
/**
* 创建单个文件
*
* @param descFileName
* 文件名,包含路径
* @return 如果创建成功,则返回true,否则返回false
*/
public static boolean createFile(String descFileName) {
File file = new File(descFileName);
if (file.exists()) {
log.debug("文件" + descFileName + "已存在!");
return false;
}
if (descFileName.endsWith(File.separator)) {
log.debug(descFileName + "为目录,不能创建目录!");
return false;
}
if (!file.getParentFile().exists()) {
// 如果文件所在的目录不存在,则创建目录
if (!file.getParentFile().mkdirs()) {
log.debug("创建文件所在的目录失败!");
return false;
}
}
// 创建文件
try {
if (file.createNewFile()) {
log.debug(descFileName + "文件创建成功!");
return true;
} else {
log.debug(descFileName + "文件创建失败!");
return false;
}
} catch (Exception e) {
e.printStackTrace();
log.debug(descFileName + "文件创建失败!");
return false;
}
}
/**
* 创建目录
*
* @param descDirName
* 目录名,包含路径
* @return 如果创建成功,则返回true,否则返回false
*/
public static boolean createDirectory(String descDirName) {
String descDirNames = descDirName;
if (!descDirNames.endsWith(File.separator)) {
descDirNames = descDirNames + File.separator;
}
File descDir = new File(descDirNames);
if (descDir.exists()) {
log.debug("目录" + descDirNames + "已存在!");
return false;
}
// 创建目录
if (descDir.mkdirs()) {
log.debug("目录" + descDirNames + "创建成功!");
return true;
} else {
log.debug("目录" + descDirNames + "创建失败!");
return false;
}
}
/**
* 压缩文件或目录
*
* @param srcDirName
* 压缩的根目录
* @param fileName
* 根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
* @param descFileName
* 目标zip文件
*/
public static void zipFiles(String srcDirName, String fileName, String descFileName) {
zipFiles(srcDirName, fileName, descFileName, null);
}
/**
* 压缩文件或目录
*
* @param srcDirName
* 压缩的根目录
* @param fileName
* 根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
* @param descFileName
* 目标zip文件
*/
public static void zipFiles(String srcDirName, String fileName, String descFileName, String encoding) {
// 判断目录是否存在
if (srcDirName == null) {
log.debug("文件压缩失败,目录" + srcDirName + "不存在!");
return;
}
File fileDir = new File(srcDirName);
if (!fileDir.exists() || !fileDir.isDirectory()) {
log.debug("文件压缩失败,目录" + srcDirName + "不存在!");
return;
}
String dirPath = fileDir.getAbsolutePath();
File descFile = new File(descFileName);
try {
ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
if (encoding != null) {
zouts.setEncoding(encoding);
}
if ("*".equals(fileName) || "".equals(fileName)) {
FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
} else {
File file = new File(fileDir, fileName);
if (file.isFile()) {
FileUtils.zipFilesToZipFile(dirPath, file, zouts);
} else {
FileUtils.zipDirectoryToZipFile(dirPath, file, zouts);
}
}
zouts.close();
log.debug(descFileName + "文件压缩成功!");
} catch (Exception e) {
log.debug("文件压缩失败:" + e.getMessage());
e.printStackTrace();
}
}
/**
* 解压缩ZIP文件,将ZIP文件里的内容解压到descFileName目录下
*
* @param zipFileName
* 需要解压的ZIP文件
* @param descFileName
* 目标文件
*/
public static boolean unZipFiles(String zipFileName, String descFileName) {
String descFileNames = descFileName;
if (!descFileNames.endsWith(File.separator)) {
descFileNames = descFileNames + File.separator;
}
try {
// 根据ZIP文件创建ZipFile对象
ZipFile zipFile = new ZipFile(zipFileName);
ZipEntry entry = null;
String entryName = null;
String descFileDir = null;
byte[] buf = new byte[4096];
int readByte = 0;
// 获取ZIP文件里所有的entry
@SuppressWarnings("rawtypes")
Enumeration enums = zipFile.getEntries();
// 遍历所有entry
while (enums.hasMoreElements()) {
entry = (ZipEntry) enums.nextElement();
// 获得entry的名字
entryName = entry.getName();
descFileDir = descFileNames + entryName;
if (entry.isDirectory()) {
// 如果entry是一个目录,则创建目录
new File(descFileDir).mkdirs();
continue;
} else {
// 如果entry是一个文件,则创建父目录
new File(descFileDir).getParentFile().mkdirs();
}
File file = new File(descFileDir);
// 打开文件输出流
OutputStream os = new FileOutputStream(file);
// 从ZipFile对象中打开entry的输入流
InputStream is = zipFile.getInputStream(entry);
while ((readByte = is.read(buf)) != -1) {
os.write(buf, 0, readByte);
}
os.close();
is.close();
}
zipFile.close();
log.debug("文件解压成功!");
return true;
} catch (Exception e) {
log.debug("文件解压失败:" + e.getMessage());
return false;
}
}
/**
* 将目录压缩到ZIP输出流
*
* @param dirPath
* 目录路径
* @param fileDir
* 文件信息
* @param zouts
* 输出流
*/
public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
if (fileDir.isDirectory()) {
File[] files = fileDir.listFiles();
// 空的文件夹
if (files.length == 0) {
// 目录信息
ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
try {
zouts.putNextEntry(entry);
zouts.closeEntry();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
// 如果是文件,则调用文件压缩方法
FileUtils.zipFilesToZipFile(dirPath, files[i], zouts);
} else {
// 如果是目录,则递归调用
FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts);
}
}
}
}
/**
* 将文件压缩到ZIP输出流
*
* @param dirPath
* 目录路径
* @param file
* 文件
* @param zouts
* 输出流
*/
public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
FileInputStream fin = null;
ZipEntry entry = null;
// 创建复制缓冲区
byte[] buf = new byte[4096];
int readByte = 0;
if (file.isFile()) {
try {
// 创建一个文件输入流
fin = new FileInputStream(file);
// 创建一个ZipEntry
entry = new ZipEntry(getEntryName(dirPath, file));
log.debug(entry.getName());
// 存储信息到压缩文件
zouts.putNextEntry(entry);
// 复制字节到压缩文件
while ((readByte = fin.read(buf)) != -1) {
zouts.write(buf, 0, readByte);
}
zouts.closeEntry();
fin.close();
System.out.println("添加文件" + file.getAbsolutePath() + "到zip文件中!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名
*
* @param dirPat
* 目录名
* @param file
* entry文件名
* @return
*/
private static String getEntryName(String dirPath, File file) {
String dirPaths = dirPath;
if (!dirPaths.endsWith(File.separator)) {
dirPaths = dirPaths + File.separator;
}
String filePath = file.getAbsolutePath();
// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
if (file.isDirectory()) {
filePath += "/";
}
int index = filePath.indexOf(dirPaths);
return filePath.substring(index + dirPaths.length());
}
}
FreeMarkers.java
/**
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package com.whty.platform.generate.codegen;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Map;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import freemarker.template.Configuration;
import freemarker.template.Template;
/**
* FreeMarkers工具类
* @author 舒海洋
* @version 2013-01-15
*/
public class FreeMarkers {
public static String renderString(String templateString, Map<String, ?> model) {
try {
StringWriter result = new StringWriter();
Template t = new Template("name", new StringReader(templateString), new Configuration());
t.process(model, result);
return result.toString();
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
public static String renderTemplate(Template template, Object model) {
try {
StringWriter result = new StringWriter();
template.process(model, result);
return result.toString();
} catch (Exception e) {
throw Exceptions.unchecked(e);
}
}
public static Configuration buildConfiguration(String directory) throws IOException {
Configuration cfg = new Configuration();
Resource path = new DefaultResourceLoader().getResource(directory);
cfg.setDirectoryForTemplateLoading(path.getFile());
return cfg;
}
public static void main(String[] args) throws IOException {
// // renderString
// Map<String, String> model = com.google.common.collect.Maps.newHashMap();
// model.put("userName", "calvin");
// String result = FreeMarkers.renderString("hello ${userName}", model);
// System.out.println(result);
// // renderTemplate
// Configuration cfg = FreeMarkers.buildConfiguration("classpath:/");
// Template template = cfg.getTemplate("testTemplate.ftl");
// String result2 = FreeMarkers.renderTemplate(template, model);
// System.out.println(result2);
// Map<String, String> model = com.google.common.collect.Maps.newHashMap();
// model.put("userName", "calvin");
// String result = FreeMarkers.renderString("hello ${userName} ${r'${userName}'}", model);
// System.out.println(result);
}
}
GenFunctions.java
package com.whty.platform.generate.codegen;
/**
* 文件操作工具类
*/
public class GenFunctions {
/**
* 将传入的字符串首字母大写
* @param str
* @return
*/
public static String firstToUpperCase(String str) {
str=str.toLowerCase();
int strLength = str.length();
if (strLength > 1) {
String post = str.substring(1, strLength);
char first = str.charAt(0);
return String.valueOf(first).toUpperCase() + post;
} else {
return str.toUpperCase();
}
}
public static void main(String[] args){
System.out.println(firstToUpperCase("USER"));
}
}
JdbcConfig.java
package com.whty.platform.generate.codegen;
/**
* JDBC配置模型
* @author 黄天政
*
*/
public class JdbcConfig {
private String driver;
private String url;
private String user;
private String password;
public JdbcConfig() {
super();
// TODO Auto-generated constructor stub
}
public JdbcConfig(String driver, String url, String user, String password) {
super();
this.driver = driver;
this.url = url;
this.user = user;
this.password = password;
}
/**
* @return 取得JDBC驱动类
*/
public String getDriver() {
return driver;
}
/**
* @param driver 设置JDBC驱动类
*/
public void setDriver(String driver) {
this.driver = driver;
}
/**
* @return 取得JDBC连接字符串
*/
public String getUrl() {
return url;
}
/**
* @param url 设置JDBC连接字符串
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return 取得JDBC连接的用户名,即当前数据库连接的属主
*/
public String getUser() {
return user;
}
/**
* @param user 设置JDBC连接的用户名,即当前数据库连接的属主
*/
public void setUser(String user) {
this.user = user;
}
/**
* @return 取得JDBC连接的密码
*/
public String getPassword() {
return password;
}
/**
* @param password 设置JDBC连接的密码
*/
public void setPassword(String password) {
this.password = password;
}
}
MysqlProvider.java
package com.whty.platform.generate.codegen;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import org.apache.commons.lang.StringUtils;
/**
* 针对Oracle的数据库信息提供者
* @author 黄天政
*
*/
public class MysqlProvider extends DbProvider {
public MysqlProvider(Connection conn) {
super(conn);
}
public MysqlProvider(JdbcConfig jdbcConfig) {
super(jdbcConfig);
}
/**
* 根据表名和库名得到该表的所有列模型
* @param tableName 表名
* @param Schema 库名
* @return
* @throws IOException
*/
public List<TableModel> getTableSCRIPTModelList(String tableName,String Schema) throws IOException{
Statement stmt = null;
ResultSet rs = null;
ResultSet rs1 = null;
String sql = "select * from Information_schema.columns where TABLE_NAME='"+tableName.toLowerCase()+"' and table_schema='"+Schema.toLowerCase()+"'";
TableModel tb=null;
List<TableModel> list=new ArrayList<TableModel>();
try{
stmt = getConn().createStatement();
rs = stmt.executeQuery(sql);
//rs1=stmt.executeQuery(sql);
String commstr="";
String priStr="";
String sqlstr="-- Create table \r\n"
+" create table "+tableName +"\r\n"
+"(\r\n";
boolean first=true;
while(rs.next()){
String column_name = rs.getString("column_name").toLowerCase(); //列名
//System.out.println(column_name);
String is_nullable = rs.getString("is_nullable").toLowerCase(); //是否允许为空
//System.out.println(is_nullable);
String column_key=rs.getString("column_key").toLowerCase(); //主键信息
//System.out.println(column_key);
String column_type = rs.getString("column_type").toLowerCase(); //数据类型
//System.out.println(column_type);
String column_comment = rs.getString("column_comment").toLowerCase(); //备注
//System.out.println(column_comment);
if(first==true){
sqlstr=sqlstr +" \r\n";
first=false;
}else{
sqlstr=sqlstr+", \r\n";
}
if(column_key.toLowerCase().equals("pri")){
sqlstr=sqlstr+column_name+" number not null ";
priStr=priStr+"alter table "+ tableName+"\r\n";
priStr=priStr+" add constraint PK_"+tableName +"_ID primary key ("+column_name+");\r\n";
}else{
sqlstr=sqlstr+column_name+" "+column_type.replace("bigint(20)", "number").replace("bigint", "number").replace("varchar", "varchar2").replace("int", "number").replace("datetime","date").replace("text", "CLOB").replace("double", "number");
if(is_nullable.equals("no")){
sqlstr=sqlstr+" not null ";
}
}
//String pri=rs.getString("column_key").toLowerCase();//主键
//String data_type = rs.getString("data_type").toLowerCase(); //数据类型
//String character_maximum_length= rs.getString("character_maximum_length").toLowerCase(); //字符长度
//String numeric_precision = rs.getString("numeric_precision").toLowerCase(); //数字长度
//String numeric_scale = rs.getString("numeric_scale").toLowerCase(); //小数位数
//String extra=rs.getString("extra").toLowerCase(); //是否自增
// String column_type_name;
// String column_type_jname;
// int column_type_num1=0;
// int column_type_num2=0;
// String []typesplit=column_type.split("\\(");
// if(typesplit.length>1){
// column_type_name=typesplit[0]; //类型名
// String column_lengths=typesplit[1];
// if(!column_lengths.equals("")){
// String []column_length=column_lengths.split("\\)");
//
// if(column_length[0].split(",").length>1){
// column_type_num1=Integer.parseInt(column_length[0].split(",")[0]);
// column_type_num2=Integer.parseInt(column_length[0].split(",")[1]);
// }else{
// column_type_num1=Integer.parseInt(column_length[0]);
// }
//
// }
// }else{
// column_type_name=column_type;
// }
// Properties po=FileUtil.initProperties("resource/datatype.properties");
// column_type_jname=po.getProperty(column_type_name);
// tb=new TableModel(column_name, is_nullable, extra, column_key, column_type, column_comment,column_type_name, column_type_jname, column_type_num1,column_type_num2);
// list.add(tb);
commstr=commstr+"comment on column "+tableName+"."+column_name+" is '"+column_comment+"';\r\n";
}
sqlstr=sqlstr+" \r\n);";
System.out.println(sqlstr);
System.out.println("-- Add comments to the columns ");
System.out.println(commstr);
System.out.println(priStr);
/*while(rs1.next()){
String column_comment = rs1.getString("column_comment").toLowerCase(); //备注
String column_name = rs1.getString("column_name").toLowerCase(); //列名
System.out.println("comment on column "+tableName+"."+column_name+" is '"+column_name+"';");
}*/
return list;
}catch(SQLException e){
e.printStackTrace();
return null;
}finally{
JdbcUtil.safelyClose(rs, stmt);
}
}
/**
* 根据表名和库名得到该表的所有列模型
* @param tableName 表名
* @param Schema 库名
* @return
* @throws IOException
*/
public List<TableModel> getTableModelList(String tableName,String Schema) throws IOException{
Statement stmt = null;
ResultSet rs = null;
String sql = "select * from Information_schema.columns where TABLE_NAME='"+tableName.toUpperCase()+"' and table_schema='"+Schema.toUpperCase()+"'";
TableModel tb=null;
List<TableModel> list=new ArrayList<TableModel>();
try{
stmt = getConn().createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
String column_name = rs.getString("column_name").toLowerCase(); //列名
String is_nullable = rs.getString("is_nullable").toLowerCase(); //是否允许为空
// String data_type = rs.getString("data_type").toLowerCase(); //数据类型
// String character_maximum_length= rs.getString("character_maximum_length").toLowerCase(); //字符长度
// String numeric_precision = rs.getString("numeric_precision").toLowerCase(); //数字长度
// String numeric_scale = rs.getString("numeric_scale").toLowerCase(); //小数位数
String extra=rs.getString("extra").toLowerCase(); //是否自增
String column_key=rs.getString("column_key").toLowerCase(); //主键信息
String column_type = rs.getString("column_type").toLowerCase(); //数据类型
String column_comment = rs.getString("column_comment").toLowerCase(); //备注
String column_type_name;
String column_type_jname;
int column_type_num1=0;
int column_type_num2=0;
String []typesplit=column_type.split("\\(");
if(typesplit.length>1){
column_type_name=typesplit[0]; //类型名
String column_lengths=typesplit[1];
if(!column_lengths.equals("")){
String []column_length=column_lengths.split("\\)");
if(column_length[0].split(",").length>1){
column_type_num1=Integer.parseInt(column_length[0].split(",")[0]);
column_type_num2=Integer.parseInt(column_length[0].split(",")[1]);
}else{
column_type_num1=Integer.parseInt(column_length[0]);
}
}
}else{
column_type_name=column_type;
}
Properties po=FileUtil.initProperties("resource/datatype.properties");
column_type_jname=po.getProperty(column_type_name);
tb=new TableModel(column_name, is_nullable, extra, column_key, column_type, column_comment,column_type_name, column_type_jname, column_type_num1,column_type_num2);
list.add(tb);
}
return list;
}catch(SQLException e){
e.printStackTrace();
return null;
}finally{
JdbcUtil.safelyClose(rs, stmt);
}
}
public List<Tables> getTablesList(String Schema) throws IOException{
Statement stmt = null;
ResultSet rs = null;
String sql = "select * from information_schema.tables t where t.table_schema='"+Schema.toLowerCase()+"'";
Tables tb=null;
List<Tables> list=new ArrayList<Tables>();
try{
stmt = getConn().createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
String table_name = rs.getString("table_name").toLowerCase(); //列名
String table_comment = rs.getString("table_comment").toLowerCase(); //是否允许为空
tb=new Tables(table_name, table_comment);
list.add(tb);
}
return list;
}catch(SQLException e){
e.printStackTrace();
return null;
}finally{
JdbcUtil.safelyClose(rs, stmt);
}
}
}
OracleProvider.java
package com.whty.platform.generate.codegen;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 针对Oracle的数据库信息提供者
*
* @author 黄天政
*
*/
public class OracleProvider extends DbProvider {
public OracleProvider(Connection conn) {
super(conn);
}
public OracleProvider(JdbcConfig jdbcConfig) {
super(jdbcConfig);
}
/**
* 根据表名和库名得到该表的所有列模型
*
* @param tableName
* 表名
* @param Schema
* 库名
* @return
* @throws IOException
*/
public List<TableModel> getTableSCRIPTModelList(String tableName,
String Schema) throws IOException {
Statement stmt = null;
ResultSet rs = null;
ResultSet rs1 = null;
String sql = "select * from Information_schema.columns where TABLE_NAME='"
+ tableName.toLowerCase()
+ "' and table_schema='"
+ Schema.toLowerCase() + "'";
TableModel tb = null;
List<TableModel> list = new ArrayList<TableModel>();
try {
stmt = getConn().createStatement();
rs = stmt.executeQuery(sql);
// rs1=stmt.executeQuery(sql);
String commstr = "";
String priStr = "";
String sqlstr = "-- Create table \r\n" + " create table "
+ tableName + "\r\n" + "(\r\n";
boolean first = true;
while (rs.next()) {
String column_name = rs.getString("column_name").toLowerCase(); // 列名
// System.out.println(column_name);
String is_nullable = rs.getString("is_nullable").toLowerCase(); // 是否允许为空
// System.out.println(is_nullable);
String column_key = rs.getString("column_key").toLowerCase(); // 主键信息
// System.out.println(column_key);
String column_type = rs.getString("column_type").toLowerCase(); // 数据类型
// System.out.println(column_type);
String column_comment = rs.getString("column_comment")
.toLowerCase(); // 备注
// System.out.println(column_comment);
if (first == true) {
sqlstr = sqlstr + " \r\n";
first = false;
} else {
sqlstr = sqlstr + ", \r\n";
}
if (column_key.toLowerCase().equals("pri")) {
sqlstr = sqlstr + column_name + " number not null ";
priStr = priStr + "alter table " + tableName + "\r\n";
priStr = priStr + " add constraint PK_" + tableName
+ "_ID primary key (" + column_name + ");\r\n";
} else {
sqlstr = sqlstr
+ column_name
+ " "
+ column_type.replace("bigint(20)", "number")
.replace("bigint", "number")
.replace("varchar", "varchar2")
.replace("int", "number")
.replace("datetime", "date")
.replace("text", "CLOB")
.replace("double", "number");
if (is_nullable.equals("no")) {
sqlstr = sqlstr + " not null ";
}
}
// String pri=rs.getString("column_key").toLowerCase();//主键
// String data_type = rs.getString("data_type").toLowerCase();
// //数据类型
// String character_maximum_length=
// rs.getString("character_maximum_length").toLowerCase();
// //字符长度
// String numeric_precision =
// rs.getString("numeric_precision").toLowerCase(); //数字长度
// String numeric_scale =
// rs.getString("numeric_scale").toLowerCase(); //小数位数
// String extra=rs.getString("extra").toLowerCase(); //是否自增
// String column_type_name;
// String column_type_jname;
// int column_type_num1=0;
// int column_type_num2=0;
// String []typesplit=column_type.split("\\(");
// if(typesplit.length>1){
// column_type_name=typesplit[0]; //类型名
// String column_lengths=typesplit[1];
// if(!column_lengths.equals("")){
// String []column_length=column_lengths.split("\\)");
//
// if(column_length[0].split(",").length>1){
// column_type_num1=Integer.parseInt(column_length[0].split(",")[0]);
// column_type_num2=Integer.parseInt(column_length[0].split(",")[1]);
// }else{
// column_type_num1=Integer.parseInt(column_length[0]);
// }
//
// }
// }else{
// column_type_name=column_type;
// }
// Properties
// po=FileUtil.initProperties("resource/datatype.properties");
// column_type_jname=po.getProperty(column_type_name);
// tb=new TableModel(column_name, is_nullable, extra,
// column_key, column_type, column_comment,column_type_name,
// column_type_jname, column_type_num1,column_type_num2);
// list.add(tb);
commstr = commstr + "comment on column " + tableName + "."
+ column_name + " is '" + column_comment + "';\r\n";
}
sqlstr = sqlstr + " \r\n);";
System.out.println(sqlstr);
System.out.println("-- Add comments to the columns ");
System.out.println(commstr);
System.out.println(priStr);
/*
* while(rs1.next()){ String column_comment =
* rs1.getString("column_comment").toLowerCase(); //备注 String
* column_name = rs1.getString("column_name").toLowerCase(); //列名
* System
* .out.println("comment on column "+tableName+"."+column_name+
* " is '"+column_name+"';"); }
*/
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
JdbcUtil.safelyClose(rs, stmt);
}
}
/**
* 根据表名和库名得到该表的所有列模型
*
* @param tableName
* 表名
* @param Schema
* 库名
* @return
* @throws IOException
*/
public List<TableModel> getTableModelList(String tableName, String Schema)
throws IOException {
Statement stmt = null;
ResultSet rs = null;
String sql = "SELECT T1.Column_Id, T2.COMMENTS,T1.NULLABLE, T1.COLUMN_NAME,T1.DATA_TYPE,T1.DATA_TYPE || '(' || T1.DATA_LENGTH || ')' as column_type,T1.DATA_LENGTH FROM USER_TAB_COLS T1, USER_COL_COMMENTS T2 WHERE T1.TABLE_NAME = T2.TABLE_NAME AND T1.COLUMN_NAME = T2.COLUMN_NAME AND T1.TABLE_NAME ='"
+ tableName.toUpperCase() + "'";
// String sql =
// "select * from Information_schema.columns where TABLE_NAME='"+tableName.toUpperCase()+"' and table_schema='"+Schema.toUpperCase()+"'";
TableModel tb = null;
List<TableModel> list = new ArrayList<TableModel>();
try {
stmt = getConn().createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String column_name = rs.getString("column_name").toLowerCase(); // 列名
String is_nullable = rs.getString("nullable").toLowerCase(); // 是否允许为空
if (is_nullable.equals("n")) {
is_nullable = "no";
} else {
is_nullable = "yes";
}
// String data_type = rs.getString("data_type").toLowerCase();
// //数据类型
// String character_maximum_length=
// rs.getString("character_maximum_length").toLowerCase();
// //字符长度
// String numeric_precision =
// rs.getString("numeric_precision").toLowerCase(); //数字长度
// String numeric_scale =
// rs.getString("numeric_scale").toLowerCase(); //小数位数
String extra = ""; // 是否自增
String column_key = ""; // 主键信息
String column_type = rs.getString("column_type").toLowerCase(); // 数据类型
String column_comment="";
if(rs.getString("comments")==null){
column_comment="";
}else{
column_comment= rs.getString("comments").toLowerCase(); // 备注
}
String column_type_name;
String column_type_jname;
int column_type_num1 = 0;
int column_type_num2 = 0;
String[] typesplit = column_type.split("\\(");
if (typesplit.length > 1) {
column_type_name = typesplit[0]; // 类型名
String column_lengths = typesplit[1];
if (!column_lengths.equals("")) {
String[] column_length = column_lengths.split("\\)");
if (column_length[0].split(",").length > 1) {
column_type_num1 = Integer
.parseInt(column_length[0].split(",")[0]);
column_type_num2 = Integer
.parseInt(column_length[0].split(",")[1]);
} else {
column_type_num1 = Integer
.parseInt(column_length[0]);
if (column_type_num1 == 22) {
column_type_name = "bigint";
}
}
}
} else {
column_type_name = column_type;
}
Properties po = FileUtil
.initProperties("resource/datatype.properties");
column_type_jname = po.getProperty(column_type_name);
tb = new TableModel(column_name, is_nullable, extra,
column_key, column_type, column_comment,
column_type_name, column_type_jname, column_type_num1,
column_type_num2);
list.add(tb);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
JdbcUtil.safelyClose(rs, stmt);
}
}
public List<Tables> getTablesList(String Schema) throws IOException {
Statement stmt = null;
ResultSet rs = null;
String sql = "select * from information_schema.tables t where t.table_schema='"
+ Schema.toLowerCase() + "'";
Tables tb = null;
List<Tables> list = new ArrayList<Tables>();
try {
stmt = getConn().createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
String table_name = rs.getString("table_name").toLowerCase(); // 列名
String table_comment = rs.getString("table_comment")
.toLowerCase(); // 是否允许为空
tb = new Tables(table_name, table_comment);
list.add(tb);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
return null;
} finally {
JdbcUtil.safelyClose(rs, stmt);
}
}
}
TableModel.java
package com.whty.platform.generate.codegen;
import java.io.Serializable;
public class TableModel implements Serializable{
private String column_name; //列名
private String is_nullable; //是否允许为空
private String extra; //是否自增 auto_increment
private String column_key; //主键信息 PRI
private String column_type; //数据类型 decimal(10,2), datetime
private String column_comment; //备注
private String column_type_name;
private String column_type_jname;
private int column_type_num1;
private int column_type_num2;
public TableModel() {
super();
// TODO Auto-generated constructor stub
}
public TableModel(String columnName, String isNullable, String extra,
String columnKey, String columnType, String columnComment,
String columnTypeName, String columnTypeJname, int columnTypeNum1,
int columnTypeNum2) {
super();
column_name = columnName;
is_nullable = isNullable;
this.extra = extra;
column_key = columnKey;
column_type = columnType;
column_comment = columnComment;
column_type_name = columnTypeName;
column_type_jname = columnTypeJname;
column_type_num1 = columnTypeNum1;
column_type_num2 = columnTypeNum2;
}
public String getColumn_name() {
return column_name;
}
public void setColumn_name(String columnName) {
column_name = columnName;
}
public String getIs_nullable() {
return is_nullable;
}
public void setIs_nullable(String isNullable) {
is_nullable = isNullable;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public String getColumn_key() {
return column_key;
}
public void setColumn_key(String columnKey) {
column_key = columnKey;
}
public String getColumn_type() {
return column_type;
}
public void setColumn_type(String columnType) {
column_type = columnType;
}
public String getColumn_comment() {
return column_comment;
}
public void setColumn_comment(String columnComment) {
column_comment = columnComment;
}
public String getColumn_type_name() {
return column_type_name;
}
public void setColumn_type_name(String columnTypeName) {
column_type_name = columnTypeName;
}
public String getColumn_type_jname() {
return column_type_jname;
}
public void setColumn_type_jname(String columnTypeJname) {
column_type_jname = columnTypeJname;
}
public int getColumn_type_num1() {
return column_type_num1;
}
public void setColumn_type_num1(int columnTypeNum1) {
column_type_num1 = columnTypeNum1;
}
public int getColumn_type_num2() {
return column_type_num2;
}
public void setColumn_type_num2(int columnTypeNum2) {
column_type_num2 = columnTypeNum2;
}
}
Tables.java
package com.whty.platform.generate.codegen;
import java.io.Serializable;
public class Tables implements Serializable{
/**
* 表名
*/
private String table_name;
/**
* 表评论
*/
private String table_comment;
public Tables() {
super();
// TODO Auto-generated constructor stub
}
public Tables(String tableName, String tableComment) {
super();
table_name = tableName;
table_comment = tableComment;
}
public String getTable_name() {
return table_name;
}
public void setTable_name(String tableName) {
table_name = tableName;
}
public String getTable_comment() {
return table_comment;
}
public void setTable_comment(String tableComment) {
table_comment = tableComment;
}
}