最近项目在做这么一件事,数据库的表的结构是动态生成的。一开始的想法是设置定时器由表结构生成mybatis的model层。所以就有了下面这些从网上借鉴的代码。
package project.PA.tool;
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.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
import project.PA.model.Person_Class;
import project.PA.service.PersonClassService;
@Component
public class BuildModelTime {
private String packageOutPath = "project.PA.model";//指定实体生成所在包的路径
private String authorName = "monster";//作者名字
private String tablename = "";//表名
private String[] colnames; // 列名数组
private String[] colTypes; //列名类型数组
private int[] colSizes; //列名大小数组
private static final String URL ="jdbc:mysql://59.77.7.247:3306/test";
private static final String NAME = "admin";
private static final String PASS = "database";
private static final String DRIVER ="com.mysql.jdbc.Driver";
private boolean f_util = false; // 是否需要导入包java.util.*
private boolean f_sql = false; // 是否需要导入包java.sql.*
public BuildModelTime(){
}
public void BuildClassTime(String name){
String tablename1=name;
tablename=name;//.substring(13);
//创建连接
Connection con=null;
//查要生成实体类的表
String sql = "select * from " + tablename1;
PreparedStatement pStemt = null;
try{
try {
Class.forName(DRIVER);
}catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
con = DriverManager.getConnection(URL,NAME,PASS);
pStemt = con.prepareStatement(sql);
ResultSetMetaData rsmd = pStemt.getMetaData();
int 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("datetime")){
f_util = true;
}
if(colTypes[i].equalsIgnoreCase("image") || colTypes[i].equalsIgnoreCase("text")){
f_sql = true;
}
colSizes[i] = rsmd.getColumnDisplaySize(i + 1);
//System.out.println(colnames[i]+","+colTypes[i]+","+colSizes[i]);
}
String content = parse(colnames,colTypes,colSizes);
try {
File directory = new File("");
//System.out.println("绝对路径:"+directory.getAbsolutePath());
//System.out.println("相对路径:"+directory.getCanonicalPath());
String path=this.getClass().getResource("").getPath();
System.out.println(path);
//System.out.println("src/?/"+path.substring(path.lastIndexOf("/com/", path.length())) );
//String outputPath = directory.getAbsolutePath()+ "/src/"+path.substring(path.lastIndexOf("/com/", path.length()), path.length()) + initcap(tablename) + ".java";
String outputPath =path.replace("tool", "model")+initcap(tablename) + ".java";// directory.getAbsolutePath()+ "/src/main/java/"+this.packageOutPath.replace(".", "/")+"/"+initcap(tablename) + ".java";
outputPath=outputPath.substring(1);
System.out.println(outputPath);
FileWriter fw = new FileWriter(outputPath);
PrintWriter pw = new PrintWriter(fw);
// pw.println(content);
pw.flush();
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
} finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 功能:生成实体类主体代码
* @param colnames
* @param colTypes
* @param colSizes
* @return
*/
private String parse(String[] colnames, String[] colTypes, int[] colSizes) {
StringBuffer sb = new StringBuffer();
//判断是否导入工具包
if(f_util){
sb.append("import java.util.Date;\r\n");
}
if(f_sql){
sb.append("import java.sql.*;\r\n");
}
sb.append("package " + this.packageOutPath + ";\r\n");
sb.append("\r\n");
//注释部分
sb.append(" /**\r\n");
sb.append(" * "+tablename+" 实体类\r\n");
sb.append(" * "+new Date()+" "+this.authorName+"\r\n");
sb.append(" */ \r\n");
//实体部分
sb.append("\r\n\r\npublic class " + initcap(tablename) + "{\r\n");
processAllAttrs(sb);//属性
processAllMethod(sb);//get set方法
sb.append("}\r\n");
//System.out.println(sb.toString());
return sb.toString();
}
/**
* 功能:生成所有属性
* @param sb
*/
private void processAllAttrs(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tprivate " + sqlType2JavaType(colTypes[i]) + " " + colnames[i] + ";\r\n");
}
}
/**
* 功能:生成所有方法
* @param sb
*/
private void processAllMethod(StringBuffer sb) {
for (int i = 0; i < colnames.length; i++) {
sb.append("\tpublic void set" + initcap(colnames[i]) + "(" + sqlType2JavaType(colTypes[i]) + " " +
colnames[i] + "){\r\n");
sb.append("\tthis." + colnames[i] + "=" + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
sb.append("\tpublic " + sqlType2JavaType(colTypes[i]) + " get" + initcap(colnames[i]) + "(){\r\n");
sb.append("\t\treturn " + colnames[i] + ";\r\n");
sb.append("\t}\r\n");
}
}
/**
* 功能:将输入字符串的首字母改成大写
* @param str
* @return
*/
private String initcap(String str) {
String[] aString=null;
aString=str.split("_");
char[] ch;
String result="";
for(int i=0;i<aString.length;i++){
ch= aString[i].toCharArray();
if (ch[0] >= 'a' && ch[0] <= 'z') {
ch[0] = (char) (ch[0] - 32);
}
result+=new String(ch);
if(i!=(aString.length-1)){
result+="_";
}
}
return result;
}
/**
* 功能:获得列的数据类型
* @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 "int";
} 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 null;
}
@Autowired
private PersonClassService personClassService;
public void buildModelFile(){
// List<Person_Class> person_Classes=personClassService.getAllPersonClass();
//
// Person_Class person_Class=new Person_Class();
// for(int i=0;i<person_Classes.size();i++){
// person_Class=person_Classes.get(i);
// BuildClassTime("person_class_"+person_Class.getClass_Name());
// }//for 遍历结果集
BuildClassTime("person_class");
return ;
}
// public static void main(String[] args) {
//
// BuildModelTime buildModelTime=new BuildModelTime();
// buildModelTime.buildModelFile();
// }
}
后来发现我的想法是很蠢的,因为我这个是spring工程要要打包成war包发布到tomcat上,晚上抄完这些代码后才发现,war包里都是.java文件编译生成的.class文件,而我竟然想要在war包里动态更新原来的.java文件。。。。。。好蠢!!。。。。。。。
PS:后来发现mybatis里可以返回hashmap,使用hashmap就能动态解决表结构一直改变的事情。(一开始还想着用jdbc去写,我怎么这么蠢!!)
上面代码出自http://www.cnblogs.com/freeliver54/archive/2013/04/15/3023195.html
谢谢大佬的代码 思路很清晰。。