想用hibernate呢,那个玩意儿又太笨重,感慨C#和PHP的舒适方便性,模拟TP写了个数据处理层,将就用着先
代码里有很多项目中的东西,不要直接COPY了。。。了解实现方法就行了
/*** @模拟TP数据操作基类框架
*@author牛牛 Q 184377367
* @20131218*/
packageModel;importjava.lang.reflect.Method;importjava.sql.ResultSet;importjava.sql.ResultSetMetaData;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importxqlbsw.DB;importxqlbsw.DataFactory;importlib.DBC;public classModelBase {publicString table;public DBC db = null;public String where = "";public String Field = "";public Boolean Delete() throwsException {
String dbChar= "delete " + this.table + " where " + this.where;
DataFactory.GDO().Update(dbChar);
DataFactory.GDO().free();return true;
}publicModelBase table(String t) {this.table =t;return this;
}publicModelBase Field(String s) {this.Field =s;return this;
}publicModelBase Where(String s) {this.where =s;return this;
}public List Select() throwsSQLException {if (this.Field == "") {this.Field = "*";
}
String dbChar= "select " + this.Field + " from " + this.table;if (this.where != "") {
dbChar+= " where " + this.where + "";
}
List list= this.toList(DataFactory.GDO().getCrmResult(dbChar));
DataFactory.GDO().free();returnlist;
}publicList toList(ResultSet rs) {
List list= newArrayList();try{//获取数据库表结构
ResultSetMetaData meta =rs.getMetaData();
Object obj= null;
String clsName= this.getClass().getName();
String aryClassName[]= clsName.split("\\.");while(rs.next()) {//获取formbean实例对象
obj =Class.forName("Domain." + aryClassName[(aryClassName.length) - 1])
.newInstance();//循环获取指定行的每一列的信息
for (int i = 1; i <= meta.getColumnCount(); i++) {//当前列名
String colName =meta.getColumnName(i);//将列名第一个字母大写(为什么加+""呢?为了把char类型转换为String类型。replace的参数是String类型。)
colName = colName.replace(colName.charAt(0) + "",new String(colName.charAt(0) + "").toUpperCase());//设置方法名
String methodName = "set" +colName;//获取当前位置的值,返回Object类型
Object value =rs.getObject(i);//利用反射机制,生成setXX()方法的Method对象并执行该setXX()方法。
Method method =obj.getClass().getMethod(methodName,
value.getClass());
method.invoke(obj, value);
}
list.add(obj);
}
}catch(Exception ex) {
ex.printStackTrace();
}finally{returnlist;
}
}
}