在实际开发中经常会先设计表,在根据表设计生成对应数据库表,再根据数据库表来编写对应实体代码。为了减少手动开发工作量已经维护表与实体对应一致性,一般使用自动生成实体。一般常用模板工具生成。这里使用Java代码生成,也是一种办法。
1、MySQL数据库
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
/**
* 根据数据库表结构生成相应的JavaBean 思路 1、创建数据库连接 2、获取数据库表、表注释 3、获取数据库表中字段名、字段类型、字段注释
* 4、构建StringBuffer缓存 5、写入文件 6、关闭连接、输入流等等
*/
public class GenEntityMySql {
private String packageOutPath = "com.gtafe.dorm.po";// 指定实体生成所在包的路径
private String dirPath = "";// 输出文件地址
private String authorName = "**";// 作者名字
private String[] tablePre = { "w_" };//表前缀【为空时输出库中所有表】
private String[] tableNames;// 表名
private String[] colsPre = {};
private String[] colnames; // 列名数组
private String[] colTypes; // 列名类型数组
private int[] colSizes; // 列名大小数组
private boolean f_util = false; // 是否需要导入包java.util.*
private boolean f_sql = false; // 是否需要导入包java.sql.*
// 数据库连接
private static final String URL = "jdbc:mysql://192.168.21.236:3307/ecloud";
private static final String NAME = "root";
private static final String PASS = "root";
private static final String DRIVER = "com.mysql.jdbc.Driver";
private Connection con = null;
private Statement pStemt = null;
private ResultSet rs = null;
private ResultSetMetaData rsmd = null;
/**
* 出口
*/
public static void main(String[] args) {
new GenEntityMySql();
}
public GenEntityMySql() {
connect();
getAllTables();
System.out.println("success");
}
/**
* 1、创建数据库连接
*/
private void connect() {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, NAME, PASS);
pStemt = (Statement) con.createStatement();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void colseConnect() {
try {
if (con != null) {
con.close();
con = null;
}
if (pStemt != null) {
pStemt.close();
pStemt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 获取所有表名
*/
private void getAllTables() {
String sql = "SELECT TABLE_NAME FROM information_schema.tables where table_schema='"
+ URL.substring(URL.lastIndexOf("/") + 1) + "'";
try {
rs = pStemt.executeQuery(sql);
String s = "";
while (rs.next()) {
s = s + rs.getString("TABLE_NAME") + ",";
}
tableNames = s.substring(0, s.length() - 1).split(",");
for (String tableName : tableNames) {
// 如果设置了表开头,则仅处理表开头的
if (tablePre.length > 0) {
boolean flag = false;
for (String pre : tablePre) {
if (tableName.startsWith(pre)) {
flag = true;
}
}
if (flag) {
getTableInfo(tableName);
}
} else {
getTableInfo(tableName);
}
f_util = false;
f_sql = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
colseConnect();
}
}
/**
* 获取单个数据库表信息
*/
private void getTableInfo(String tableName) {
int size = 0;
String sql = "SELECT * FROM " + tableName;
try {
rs = pStemt.executeQuery(sql);
rsmd = rs.getMetaData();
size = rsmd.getColumnCount();
colnames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
for (int i = 0; i < size; i++) {
colnames[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
if (colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("timestamp")) {
f_util = true;
}
if (colTypes[i].equalsIgnoreCase("blob") || colTypes[i].equalsIgnoreCase("char")) {
f_sql = true;
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
// 规范化表名
String normTableName = normTableName(tableName);
// 获取单张数据库表注释
String tableComment = getTableComment(tableName);
// 获取单张数据库表的所有列信息
StringBuffer tempSb = getColsInfo(tableName);
// 生成JavaBean文件
genFile(normTableName, getSb(tableName, normTableName, tableComment, tempSb));
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 规范类名
*
* @param tableName
* @return
*/
public String normTableName(String tableName) {
String result = "";
for (String temp : tablePre) {
int index = tableName.indexOf(temp);
if (index == 0) {
if(!temp.equals(tableName)){//(单名字与前缀相同时,按默认处理)
tableName = tableName.substring(index + temp.length());
}
String[] names = tableName.split("_");
if (null != names && names.length > 0) {
for (String name : names) {
result += captureName(name.toLowerCase());
}
}
}
}
return result;
}
/**
* 获取单张数据库表注释
*
* @param tableName
* @return
*/
private String getTableComment(String tableName) {
String str = "";
String sql = "SELECT table_comment FROM information_schema.tables where table_schema='"
+ URL.substring(URL.lastIndexOf("/") + 1) + "' and table_name = '" + tableName + "'";
try {
rs = pStemt.executeQuery(sql);
while (rs.next()) {
str = rs.getString("table_comment");
if (null != str && str.indexOf("\r\n") != -1) {
str = str.replace("\r\n", "");
}
if (null != str && str.indexOf("\n") != -1) {
str = str.replace("\n", "");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
/**
* 获取单张数据库表的所有列信息
*
* @param tableName
*/
private StringBuffer getColsInfo(String tableName) {
StringBuffer temp = new StringBuffer();
processAllAttrs(tableName, temp);// 属性
processAllMethod(temp);// get set方法
return temp;
}
/**
* 生成所有属性
*/
private void processAllAttrs(String tableName, StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
// 获取注释
if (i == 0) {
sb.append("\t@Id\r\n");
sb.append("\t@GenericGenerator(name = \"session_info_uuid_gen\", strategy = \"assigned\")\r\n");
sb.append("\t@GeneratedValue(generator = \"session_info_uuid_gen\")\r\n");
}
sb.append("\t//" + getColComment(tableName, colnames[i]) + "\r\n");
// 添加注解
sb.append("\t@Column(name = \"" + colnames[i] + "\")\r\n");
// 获取属性
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + getColsName(colnames[i]) + ";\r\n");
sb.append("\t\r\n");
}
}
/**
* 生成所有方法
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tpublic void set" + captureName(getColsName(colnames[i])) + "(" + sqlType2JavaType(colTypes[i])
+ " " + getColsName(colnames[i]) + "){\r\n");
sb.append("\t\tthis." + getColsName(colnames[i]) + "=" + getColsName(colnames[i]) + ";\r\n");
sb.append("\t}\r\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + captureName(getColsName(colnames[i]))
+ "(){\r\n");
sb.append("\t\treturn " + getColsName(colnames[i]) + ";\r\n");
sb.append("\t}\r\n");
}
}
/**
* 获取列类型
*
* @param sqlType
* @return
*/
private String sqlType2JavaType(String sqlType) {
if (sqlType.equalsIgnoreCase("bit")) {
return "Boolean";
} else if (sqlType.equalsIgnoreCase("tinyint")) {
return "Byte";
} else if (sqlType.equalsIgnoreCase("smallint")) {
return "Short";
} else if (sqlType.equalsIgnoreCase("int")) {
return "Integer";
} else if (sqlType.equalsIgnoreCase("bigint")) {
return "Long";
} else if (sqlType.equalsIgnoreCase("float")) {
return "Float";
} else if (sqlType.equalsIgnoreCase("decimal") || sqlType.equalsIgnoreCase("numeric")
|| sqlType.equalsIgnoreCase("real") || sqlType.equalsIgnoreCase("money")
|| sqlType.equalsIgnoreCase("smallmoney")) {
return "Double";
} else if (sqlType.equalsIgnoreCase("varchar") || sqlType.equalsIgnoreCase("char")
|| sqlType.equalsIgnoreCase("nvarchar") || sqlType.equalsIgnoreCase("nchar")
|| sqlType.equalsIgnoreCase("text")) {
return "String";
} else if (sqlType.equalsIgnoreCase("datetime")) {
return "Date";
} else if (sqlType.equalsIgnoreCase("image")) {
return "Blod";
}
return "String";
}
/**
* 获取列名及驼峰处理
*
* @param str
* @return
*/
private String getColsName(String str) {
if (colsPre.length > 0) {
for (String temp : colsPre) {
int preIndex = str.indexOf(temp);
if (preIndex >= 0) {
str = str.substring(preIndex + temp.length());
}
}
}
return UnderlineToHump(str);
}
/**
* 获取列注释
*
* @param tableName
* @param columnName
* @return
*/
private String getColComment(String tableName, String columnName) {
String str = "";
String sql = "select column_comment from information_schema.columns where table_schema='"
+ URL.substring(URL.lastIndexOf("/") + 1) + "' and table_name='" + tableName + "' and column_name= '"
+ columnName + "'";
try {
rs = pStemt.executeQuery(sql);
while (rs.next()) {
str = rs.getString("column_comment");
if (null != str && str.indexOf("\r\n") != -1) {
str = str.replace("\r\n", "");
}
if (null != str && str.indexOf("\n") != -1) {
str = str.replace("\n", "");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
/**
* 构建StringBuffer缓存
*
* @param tableName
* @param tableComment
* @param colSb
* @return
*/
private StringBuffer getSb(String tableName, String normTableName, String tableComment, StringBuffer colSb) {
StringBuffer sb = new StringBuffer();
sb.append("package " + this.packageOutPath + ";\r\n");
// 判断是否导入工具包
if (f_util) {
sb.append("import java.util.Date;\r\n");
}
if (f_sql) {
sb.append("import java.sql.*;\r\n");
}
// 添加通用引用
sb.append("import javax.persistence.Column;\r\n");
sb.append("import javax.persistence.Entity;\r\n");
sb.append("import javax.persistence.GeneratedValue;\r\n");
sb.append("import javax.persistence.Id;\r\n");
sb.append("import javax.persistence.Table;\r\n");
sb.append("import org.hibernate.annotations.GenericGenerator;\r\n");
sb.append("import java.io.Serializable;\r\n");
sb.append("\r\n");
// 注释部分
sb.append("/**\r\n");
sb.append("* " + normTableName + " 实体类 " + tableComment + "\r\n");
sb.append("* " + new Date() + "\r\n");
sb.append("* @author " + this.authorName + "\r\n");
sb.append("*/ \r\n");
// 注解
sb.append("@Entity\r\n");
sb.append("@Table(name = \"" + tableName + "\")\r\n");
// 实体部分
sb.append("public class " + normTableName + " implements Serializable {\r\n");
sb.append("\tprivate static final long serialVersionUID = 1L;\r\n");
sb.append(colSb);
sb.append("}\r\n");
return sb;
}
/**
* 生成JavaBean文件
*
* @param content
*/
private void genFile(String tableName, StringBuffer content) {
try {
File directory = new File("");
String path = "".equals(dirPath) ? directory.getAbsolutePath() + "/src/main/java/" : dirPath;
path = path + this.packageOutPath.replace(".", "/") + "/";
GenEntityMySql.dirExists(path);
String outputPath = path + tableName + ".java";
// GenEntityMySql.fileExists(outputPath);
FileWriter fw = new FileWriter(outputPath);
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 首字母大写
*
* @param name
* @return
*/
public static String captureName(String name) {
char[] cs = name.toCharArray();
if (cs[0] >= 'a' && cs[0] <= 'z') {
cs[0] -= 32;
}
return String.valueOf(cs);
}
/**
* 判断文件是否存在
*/
public static void fileExists(String path) {
File file = new File(path);
if (file.exists()) {
// System.out.println("file exists");
} else {
System.out.println("file not exists, create it ...");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断文件夹是否存在
*/
public static void dirExists(String path) {
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
// System.out.println("dir exists");
} else {
System.out.println("the same name file exists, can not create dir");
}
} else {
System.out.println("dir not exists, create it ...");
file.mkdirs();
}
}
/**
* 下划线命名转为驼峰命名
*/
public static String UnderlineToHump(String para) {
StringBuilder result = new StringBuilder();
String a[] = para.split("_");
for (String s : a) {
if (result.length() == 0) {
result.append(s.toLowerCase());
} else {
result.append(s.substring(0, 1).toUpperCase());
result.append(s.substring(1).toLowerCase());
}
}
return result.toString();
}
/**
* 驼峰命名转为下划线命名
*/
public static String HumpToUnderline(String para) {
StringBuilder sb = new StringBuilder(para);
int temp = 0;// 定位
for (int i = 0; i < para.length(); i++) {
if (Character.isUpperCase(para.charAt(i))) {
sb.insert(i + temp, "_");
temp += 1;
}
}
return sb.toString().toUpperCase();
}
}
2、Oracle数据库
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
/**
* 根据数据库表结构生成相应的JavaBean
*
* 思路 1、创建数据库连接 2、获取数据库表、表注释 3、获取数据库表中字段名、字段类型、字段注释 4、构建StringBuffer缓存 5、写入文件
* 6、关闭连接、输入流等等
*/
public class GenEntityOracle {
private String packageOutPath = "com.gtafe.dorm.po";// 指定实体生成所在包的路径
private String dirPath = "";// 输出文件地址
private String authorName = "**";// 作者名字
private String[] tableNames;
private String[] tablePre = { "TJOB_" };//表前缀【为空时输出库中所有表】
private String[] colsPre = {};
private String[] colnames; // 列名数组
private String[] colTypes; // 列名类型数组
private int[] colSizes; // 列名大小数组
private boolean f_util = false; // 是否需要导入包java.util.*
private boolean f_sql = false; // 是否需要导入包java.sql.*
// 数据库连接
private static final String URL = "jdbc:oracle:thin:@10.1.137.12:1521:orcl";
private static final String NAME = "UGTA_NEW";
private static final String PASS = "GTAgta123";
private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
private Connection con = null;
private Statement pStemt = null;
private ResultSet rs = null;
private ResultSetMetaData rsmd = null;
/**
* 出口
*/
public static void main(String[] args) {
new GenEntityOracle();
}
public GenEntityOracle() {
connect();
getAllTables();
System.out.println("success");
}
/**
* 1、创建数据库连接
*/
private void connect() {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, NAME, PASS);
pStemt = (Statement) con.createStatement();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void colseConnect() {
try {
if (con != null) {
con.close();
con = null;
}
if (pStemt != null) {
pStemt.close();
pStemt = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 获取所有表名
*/
private void getAllTables() {
String sql = "SELECT TABLE_NAME FROM USER_TABLES";
try {
rs = pStemt.executeQuery(sql);
String s = "";
while (rs.next()) {
s = s + rs.getString("TABLE_NAME") + ",";
}
tableNames = s.substring(0, s.length() - 1).split(",");
for (String tableName : tableNames) {
// 如果设置了表开头,则仅处理表开头的
if (tablePre.length > 0) {
boolean flag = false;
for (String pre : tablePre) {
if (tableName.startsWith(pre)) {
flag = true;
}
}
if (flag) {
getTableInfo(tableName);
}
} else {
getTableInfo(tableName);
}
f_util = false;
f_sql = false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
colseConnect();
}
}
/**
* 获取单个数据库表信息
*/
private void getTableInfo(String tableName) {
int size = 0;
String sql = "SELECT * FROM " + tableName;
try {
rs = pStemt.executeQuery(sql);
rsmd = rs.getMetaData();
size = rsmd.getColumnCount();
colnames = new String[size];
colTypes = new String[size];
colSizes = new int[size];
for (int i = 0; i < size; i++) {
colnames[i] = rsmd.getColumnName(i + 1);
colTypes[i] = rsmd.getColumnTypeName(i + 1);
if (colTypes[i].equalsIgnoreCase("date") || colTypes[i].equalsIgnoreCase("timestamp")) {
f_util = true;
}
if (colTypes[i].equalsIgnoreCase("blob") || colTypes[i].equalsIgnoreCase("char")) {
f_sql = true;
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
}
// 规范化表名
String normTableName = normTableName(tableName);
// 获取单张数据库表注释
String tableComment = getTableComment(tableName);
// 获取单张数据库表的所有列信息
StringBuffer tempSb = getColsInfo(tableName);
// 生成JavaBean文件
genFile(normTableName, getSb(tableName, normTableName, tableComment, tempSb));
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 规范类名
*
* @param tableName
* @return
*/
public String normTableName(String tableName) {
String result = "";
for (String temp : tablePre) {
int index = tableName.indexOf(temp);
if (index >= 0) {
if(!temp.equals(tableName)){//(单名字与前缀相同时,按默认处理)
tableName = tableName.substring(index + temp.length());
}
String[] names = tableName.split("_");
if (null != names && names.length > 0) {
for (String name : names) {
result += captureName(name.toLowerCase());
}
}
}
}
return result;
}
/**
* 获取单张数据库表注释
*
* @param tableName
* @return
*/
private String getTableComment(String tableName) {
String str = "";
String sql = "select * from user_tab_comments where table_name = '" + tableName + "'";
try {
rs = pStemt.executeQuery(sql);
while (rs.next()) {
str = rs.getString("comments");
if (null != str && str.indexOf("\r\n") != -1) {
str = str.replace("\r\n", "");
}
if (null != str && str.indexOf("\n") != -1) {
str = str.replace("\n", "");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
/**
* 获取单张数据库表的所有列信息
*
* @param tableName
*/
private StringBuffer getColsInfo(String tableName) {
StringBuffer temp = new StringBuffer();
processAllAttrs(tableName, temp);// 属性
processAllMethod(temp);// get set方法
return temp;
}
/**
* 生成所有属性
*/
private void processAllAttrs(String tableName, StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
// 获取注释
if (i == 0) {
sb.append("\t@Id\r\n");
sb.append("\t@GenericGenerator(name = \"session_info_uuid_gen\", strategy = \"assigned\")\r\n");
sb.append("\t@GeneratedValue(generator = \"session_info_uuid_gen\")\r\n");
}
sb.append("\t//" + getColComment(tableName, colnames[i]) + "\r\n");
// 添加注解
sb.append("\t@Column(name = \"" + colnames[i] + "\")\r\n");
// 获取属性
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + getColsName(colnames[i]) + ";\r\n");
sb.append("\t\r\n");
}
}
/**
* 生成所有方法
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tpublic void set" + captureName(getColsName(colnames[i])) + "(" + sqlType2JavaType(colTypes[i])
+ " " + getColsName(colnames[i]) + "){\r\n");
sb.append("\t\tthis." + getColsName(colnames[i]) + "=" + getColsName(colnames[i]) + ";\r\n");
sb.append("\t}\r\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + captureName(getColsName(colnames[i]))
+ "(){\r\n");
sb.append("\t\treturn " + getColsName(colnames[i]) + ";\r\n");
sb.append("\t}\r\n");
}
}
/**
* 获取列类型
*
* @param sqlType
* @return
*/
private String sqlType2JavaType(String sqlType) {
if (sqlType.equalsIgnoreCase("binary_double")) {
return "Double";
} else if (sqlType.equalsIgnoreCase("binary_float")) {
return "Float";
} else if (sqlType.equalsIgnoreCase("blob")) {
return "Byte[]";
} else if (sqlType.equalsIgnoreCase("char") || sqlType.equalsIgnoreCase("nvarchar2")
|| sqlType.equalsIgnoreCase("varchar2")) {
return "String";
} else if (sqlType.equalsIgnoreCase("date") || sqlType.equalsIgnoreCase("timestamp")
|| sqlType.equalsIgnoreCase("timestamp with local time zone")
|| sqlType.equalsIgnoreCase("timestamp with time zone")) {
return "Date";
} else if (sqlType.equalsIgnoreCase("number")) {
return "Long";
}
return "String";
}
/**
* 获取列名及驼峰处理
*
* @param str
* @return
*/
private String getColsName(String str) {
if (colsPre.length > 0) {
for (String temp : colsPre) {
int preIndex = str.indexOf(temp);
if (preIndex >= 0) {
str = str.substring(preIndex + temp.length());
}
}
}
return UnderlineToHump(str);
}
/**
* 获取列注释
*
* @param tableName
* @param columnName
* @return
*/
private String getColComment(String tableName, String columnName) {
String str = "";
String sql = "select comments from USER_COL_COMMENTS where table_name= '" + tableName + "' and column_name= '"
+ columnName + "'";
try {
rs = pStemt.executeQuery(sql);
while (rs.next()) {
str = rs.getString("comments");
if (null != str && str.indexOf("\r\n") != -1) {
str = str.replace("\r\n", "");
}
if (null != str && str.indexOf("\n") != -1) {
str = str.replace("\n", "");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return str;
}
/**
* 构建StringBuffer缓存
*
* @param tableName
* @param tableComment
* @param colSb
* @return
*/
private StringBuffer getSb(String tableName, String normTableName, String tableComment, StringBuffer colSb) {
StringBuffer sb = new StringBuffer();
sb.append("package " + this.packageOutPath + ";\r\n");
// 判断是否导入工具包
if (f_util) {
sb.append("import java.util.Date;\r\n");
}
if (f_sql) {
sb.append("import java.sql.*;\r\n");
}
// 添加通用引用
sb.append("import javax.persistence.Column;\r\n");
sb.append("import javax.persistence.Entity;\r\n");
sb.append("import javax.persistence.GeneratedValue;\r\n");
sb.append("import javax.persistence.Id;\r\n");
sb.append("import javax.persistence.Table;\r\n");
sb.append("import org.hibernate.annotations.GenericGenerator;\r\n");
sb.append("import java.io.Serializable;\r\n");
sb.append("\r\n");
// 注释部分
sb.append("/**\r\n");
sb.append("* " + normTableName + " 实体类 " + tableComment + "\r\n");
sb.append("* " + new Date() + "\r\n");
sb.append("* @author " + this.authorName + "\r\n");
sb.append("*/ \r\n");
// 注解
sb.append("@Entity\r\n");
sb.append("@Table(name = \"" + tableName + "\")\r\n");
// 实体部分
sb.append("public class " + normTableName + " implements Serializable {\r\n");
sb.append("\tprivate static final long serialVersionUID = 1L;\r\n");
sb.append(colSb);
sb.append("}\r\n");
return sb;
}
/**
* 生成JavaBean文件
*
* @param content
*/
private void genFile(String tableName, StringBuffer content) {
try {
File directory = new File("");
String path = "".equals(dirPath) ? directory.getAbsolutePath() + "/src/main/java/" : dirPath;
path = path + this.packageOutPath.replace(".", "/") + "/";
GenEntityOracle.dirExists(path);
String outputPath = path + tableName + ".java";
// GenEntityOracle.fileExists(outputPath);
FileWriter fw = new FileWriter(outputPath);
PrintWriter pw = new PrintWriter(fw);
pw.println(content);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 首字母大写
*
* @param name
* @return
*/
public static String captureName(String name) {
char[] cs = name.toCharArray();
if (cs[0] >= 'a' && cs[0] <= 'z') {
cs[0] -= 32;
}
return String.valueOf(cs);
}
/**
* 判断文件是否存在
*/
public static void fileExists(String path) {
File file = new File(path);
if (file.exists()) {
// System.out.println("file exists");
} else {
System.out.println("file not exists, create it ...");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断文件夹是否存在
*/
public static void dirExists(String path) {
File file = new File(path);
if (file.exists()) {
if (file.isDirectory()) {
// System.out.println("dir exists");
} else {
System.out.println("the same name file exists, can not create dir");
}
} else {
System.out.println("dir not exists, create it ...");
file.mkdirs();
}
}
/**
* 下划线命名转为驼峰命名
*/
public static String UnderlineToHump(String para) {
StringBuilder result = new StringBuilder();
String a[] = para.split("_");
for (String s : a) {
if (result.length() == 0) {
result.append(s.toLowerCase());
} else {
result.append(s.substring(0, 1).toUpperCase());
result.append(s.substring(1).toLowerCase());
}
}
return result.toString();
}
/**
* 驼峰命名转为下划线命名
*/
public static String HumpToUnderline(String para) {
StringBuilder sb = new StringBuilder(para);
int temp = 0;// 定位
for (int i = 0; i < para.length(); i++) {
if (Character.isUpperCase(para.charAt(i))) {
sb.insert(i + temp, "_");
temp += 1;
}
}
return sb.toString().toUpperCase();
}
}