为了根据数据库表,自动生成EO对象,自已经写了一段代码,步骤如下生成:
第一步:新建jdbc.properties文件,内容如下, 主要为后续配置处理
dataSource.url=jdbc:mysql://localhost:3306/test
dataSource.password=1234
dataSource.username=rootgenerate.tablenames=t_job ###相应需要生成的表名,有多个时以','隔开generate.path=D:/work/workplace/WiFiPlaning/src ##工程的scr目录
第二步:如下的java类 GenerateEntity
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import java.io.FileWriter;
/**
*
* @GenerateEntity
*/
public class GenerateEntity {
//properties
private static ResourceBundle messages = ResourceBundle.getBundle("jdbc");
/**bean需要添加的后缀*/
private static String BeanName = "Entity";
private static final String jdbcString = messages
.getString("dataSource.url");
private static final String userName = messages
.getString("dataSource.username");
private static final String password = messages
.getString("dataSource.password");
/**
* 用于调试,懒得写相应的参数
*
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
Connection connection = null;
connection = DriverManager
.getConnection(jdbcString, userName, password);
return connection;
}
/**
* generate String for table
* @param tableName
* @param packageName
* @param className
* @return
* @throws SQLException
*/
public static String table2pojo(String tableName,String packageName,String className) throws SQLException {
String sql = "select * from " + tableName + " where 1 <> 1";
PreparedStatement ps = null;
ResultSet rs = null;
Connection connection = null;
try {
connection = GenerateEntity.getConnection();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
}
ps = connection.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
StringBuffer sb = new StringBuffer();
StringBuffer importStr = new StringBuffer();
importStr.append("package " + packageName + LINE + LINE);
importStr.append("import javax.persistence.Column;" + LINE);
importStr.append("import javax.persistence.Entity;" + LINE);
importStr.append("import javax.persistence.Id;" + LINE);
importStr.append("import javax.persistence.Table;" + LINE);
boolean haveDate = false;
boolean haveBigDecimal = false;
sb.append("@Entity");
sb.append(LINE);
sb.append("@Table(name = \"" + tableName + "\")");
sb.append(LINE);
className = generateClassName(className,tableName);
sb.append("public class " + className + " {");
sb.append(LINE);
for (int i = 1; i <= columnCount; i++) {
sb.append(LINE);
String coumnType = GenerateEntity.getPojoType(md
.getColumnTypeName(i));
// 对于日期处理
if (haveDate == false && "Date".equals(coumnType)) {
haveDate = true;
importStr.append(importDateStr + LINE);
importStr.append("import javax.persistence.Temporal;" + LINE);
importStr.append("import javax.persistence.TemporalType;"
+ LINE);
sb.append(TAB);
sb.append("@Temporal(TemporalType.TIMESTAMP)");
// 对于number的处理
} else if (haveBigDecimal == false
&& "BigDecimal".equals(coumnType)) {
importStr.append(importBigDecimaleStr + LINE);
}
sb.append(TAB);
sb.append("@Column(name=\"" + md.getColumnName(i) + "\")");
// System.out.println(md.getColumnLabel(i));
sb.append(TAB);
sb.append(LINE);
sb.append(TAB);
sb.append("/**" + md.getColumnName(i) + "*/");
sb.append(LINE);
sb.append(TAB);
sb.append("private " + coumnType + " " + md.getColumnName(i) + ";");
sb.append(LINE);
}
for (int i = 1; i <= columnCount; i++) {
sb.append(TAB);
String pojoType = GenerateEntity.getPojoType(md
.getColumnTypeName(i));
String columnName = convertFieldName(md.getColumnName(i));
String getName = null;
String setName = null;
if (columnName.length() > 1) {
getName = "public " + pojoType + " get"
+ columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1, columnName.length()) + "() {";
setName = "public void set"
+ columnName.substring(0, 1).toUpperCase()
+ columnName.substring(1, columnName.length()) + "("
+ pojoType + " " + columnName + ") {";
} else {
getName = "public get" + columnName.toUpperCase() + "() {";
setName = "public set" + columnName.toUpperCase() + "("
+ pojoType + " " + columnName + ") {";
}
sb.append(LINE).append(TAB).append(getName);
sb.append(LINE).append(TAB).append(TAB);
sb.append("return " + columnName + ";");
sb.append(LINE).append(TAB).append("}");
sb.append(LINE);
sb.append(LINE).append(TAB).append(setName);
sb.append(LINE).append(TAB).append(TAB);
sb.append("this." + columnName + " = " + columnName + ";");
sb.append(LINE).append(TAB).append("}");
sb.append(LINE);
}
sb.append("}");
importStr.append(LINE+ sb.toString());
return importStr.toString();
}
private static Map<String, String> map;
static {
map = new HashMap<String, String>();
map.put("varchar", "String");
map.put("int", "Integer");
map.put("datetime", "Date");
map.put("date", "Date");
map.put("nvarchar", "String");
map.put("char", "String");
map.put("uniqueidentifier", "String");
map.put("number", "BigDecimal");
map.put("decimal", "BigDecimal");
map.put("bigint", "Long");
map.put("tinyint", "Boolean");
}
private static final String LINE = "\r\n";
private static final String TAB = "\t";
private static final String importDateStr = "import java.util.Date;";
private static final String importBigDecimaleStr = "import java.math.BigDecimal;";
public static String getPojoType(String dataType) {
String tmp = dataType.toLowerCase();
StringTokenizer st = new StringTokenizer(tmp);
return map.get(st.nextToken());
}
/***************************************************************************
* 将s_name 变为 sName;
*
* @param sName
* @return
*/
public static String convertFieldName(String sName) {
String[] str = sName.toLowerCase().split("_");
StringBuffer beanS = new StringBuffer(str[0]);
for (int i = 1; i < str.length; i++) {
if ("".equals(str) || str == null) {
continue;
}
String info = str[i];
beanS.append(info.substring(0, 1).toUpperCase()
+ info.substring(1, info.length()));
}
return beanS.toString();
}
/**
* 生成类名
* @param className
* @return
*/
private static String generateClassName(String className,String tableName){
if(className ==null || "".equals(className))
className = convertFieldName(tableName) + BeanName;
return className;
}
/***
* 入口函数
* @param args
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
String strTables = messages.getString("generate.tablenames");
String packageName = messages.getString("generate.packagename");
String src= messages.getString("generate.path");
for( String tableName:strTables.split(",")){
try {
String className = generateClassName(null,tableName);
String classInfo = GenerateEntity.table2pojo(tableName, packageName,className);
System.out.println(classInfo);
String fileName = src + packageName.replace(".", "/") + className + ".java";
FileWriter writer;
writer = new FileWriter(fileName);
writer.write(classInfo);
writer.close();
System.out.println("GenerateEntity:" + fileName);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}