您的位置:首页 > 编程语言 > Java开发

Java 反射机制模拟hibernate实现持久化

2011-05-20 22:04 375 查看
转自:http://blog.csdn.net/ljjlzx/archive/2009/07/29/4390628.aspx

hibernate 可以使我们轻松的进行数据库的操作,
传递一个查询语句(类似 "select id,name from userInfo"),hibernate 会自动的将符合条件的
对象封装的list里面,供我们调用,大大简化了我们的代码量。下面就以一段代码模仿hibernate
的实现。

代码片段一(一般的查询方法):
/**
* 通用的查询方法
* 通过SQL语句,与传递进来的object
* 将查询出来的sql结果,通过反射机制封装至object
* 注: ojbect必须为POJO,或BEAN的类
* @param sql 查询SQL
* @param objName 需要返回的列表内包含对象的类型
* @return 封装好的对象
*/
public List getResult(String sql,String objName,int db_flag) throws Exception
{

PreparedStatement stmt = null;
ResultSet rs = null;
RecordReflection rr = null;

//获得数据库的连接
dbConnection = new DbConn1().getDBConnection();
if(dbConnection != null) System.out.println("GetConn successful");

List result = null;
try {
stmt = dbConnection.prepareStatement(sql);
rs = stmt.executeQuery();
if(rs != null){
System.out.println("GetRS successful");
}
//具体内容见代码片段2
rr = new RecordReflection();
//通过传递 结果集 和 “对象的全名” 返回 对象列表,和 普通查询 这一步不同
result = rr.Relection(rs, objName);

} catch (SQLException ex) {
log.error("getResult is error:" + ex.getMessage());
ex.printStackTrace();
} finally {
this.closeResultSet(rs);
this.closeStatement(stmt);
this.closeConnection();
}

return result;    //返回范类型集合,该集合中存储着符合条件的行与列
}
 

代码片段二(RecordReflection 类):
package com.ghrt.frame;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
public class RecordReflection {
private Logger log = Logger.getLogger(RecordReflection.class);
/**
* 通过传递进来的ResultSet与对象名称,序列化为对象,塞入list
* @param rs 结果集
* @param objName 对象
* @return list list里存储传递的objName的对象
*/
public List Relection(ResultSet rs,String objName){
List list = null;
try{
List resultList = this.ProcessResultSet(rs);
list = this.ProcessObject(resultList, objName);

}catch(Exception e){
log.error("Relection is error:" + e.getMessage());
}
return list;
}
public List ProcessResultSet(ResultSet rs) throws PlatformException{

List listResult =new ArrayList();
int cols = 0;
String colName="";
String colType="";
String colValue="";
try{
if(rs == null) //判断是否结果集为空,如果为空,直接返回
return null;

LabelValue lv = null; //见代码片段3

List list = new ArrayList<LabelValue>();
ResultSetMetaData rsetMd = null;
rsetMd = rs.getMetaData();
cols = rsetMd.getColumnCount();
while(rs.next()){

list = new ArrayList<LabelValue>();
for (int i=0;i<cols;i++){
colName = rsetMd.getColumnName(i+1);
colType = rsetMd.getColumnTypeName(i+1);
colValue = rs.getString(i+1);
lv = new LabelValue();
lv.setName(colName);
lv.setType(colType);
lv.setValue(colValue);

list.add(lv);
}

listResult.add(list);
}
}catch(Exception e){
log.error(" // Relection process ResultSet is error // " + e.getMessage());
throw new PlatformException("class RecordReflection ProcessResultSet is error: " + e.getMessage());
}
return listResult;
}
public List ProcessObject(List list,String objName) throws PlatformException{

List resultList = null;
try{
resultList = new ArrayList();
log.debug(" // list.size:" + list.size());
Iterator it = list.iterator();

while(it.hasNext()){//获取每条记录
List lvList = (List)it.next();
log.debug(" // lvList.size:" + lvList.size());

System.out.println("lvList:"+lvList.size());
Iterator lvIt = lvList.iterator();

Class clazz = Class.forName(objName);
Object obj = clazz.newInstance();

while(lvIt.hasNext()){//获取记录里的每个字段
LabelValue lv = (LabelValue)lvIt.next();
//获取生成的object对象

Field[] fields = clazz.getDeclaredFields();
log.debug("// fileds.length // "+fields.length);
//      for(Field field:fields){
for(int i = 0;i<fields.length;i++){
Field field = fields[i];
System.out.println(fields[i]);
log.debug("getname:"+field.getName()+" // lv.getName // "+lv.getName());
String fieldName = field.getName();

if(fieldName.equalsIgnoreCase(lv.getName())){
log.debug(" // fieldName//" + fieldName +" // fieldType //" + field.getType().getName());
log.debug(" // lv.getName // " + lv.getName() + " // lv.value // " + lv.getValue());
Method method = clazz.getDeclaredMethod(                                     "set"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1)
,new Class[]{field.getType()});
if(field.getType().equals(String.class)){
//处理当为String类型情况
method.invoke(obj, new Object[]{this.toString(lv.getValue())});
}else if(field.getType().equals(Integer.class)){
//处理当为Integer类型情况
method.invoke(obj, new Object[]{this.toInteger(lv.getValue())});
}else if(field.getType().equals(Float.class)){
//处理当为Float类型情况
method.invoke(obj, new Object[]{this.toFloat(lv.getValue())});
}else if(field.getType().equals(Double.class)){
//处理当为Double类型情况
method.invoke(obj, new Object[]{this.toDouble(lv.getValue())});
}else if(field.getType().equals(BigDecimal.class)){
//处理当为BigDecimal类型情况
method.invoke(obj, new Object[]{this.toBigDecimal(lv.getValue())});
}else if(field.getType().equals(Long.class)){
//处理当为Long类型情况
method.invoke(obj, new Object[]{this.toLong(lv.getValue())});
}else if(field.getType().equals(Timestamp.class)){
//处理当为Timestamp类型情况
method.invoke(obj, new Object[]{this.toTimestamp(lv.getValue())});
}else if(field.getType().equals(int.class)){
//处理当为int类型情况
method.invoke(obj, new Object[]{this.toInteger(lv.getValue())});
}else if(field.getType().equals(float.class)){
//处理当为float类型情况
method.invoke(obj, new Object[]{this.toFloat(lv.getValue())});
}else if(field.getType().equals(double.class)){
//处理当为double类型情况
method.invoke(obj, new Object[]{this.toDouble(lv.getValue())});
}else if(field.getType().equals(Date.class)){
//处理当为Date类型情况
method.invoke(obj, new Object[]{this.toTimestamp(lv.getValue())});
}else if(field.getType().equals(short.class)){
//处理当为Short类型情况
log.debug(" // parse short // ");
method.invoke(obj, new Object[]{this.toShort(lv.getValue())});
}

}

}
}

resultList.add(obj);
}
}catch(Exception ex){
log.error(" // process object is error // " + ex.getMessage());
throw new PlatformException("class RecordReflection ProcessObject is error: " + ex.getMessage());
}
return resultList;
}
/**
* 对Date类型转换
* @param args
* @return
*/
public Date toDate(String args){
Date result = null;
if(null == args || "".equals(args))
result = null;
else
try{
//     result = BigDecimal.parseBigDecimal(args);
result = new Date(args);
}catch(Exception e){
result = null;
log.error(" // RecordReflection parse Date is error // " + e.getMessage());
}

return result;
}
/**
* 对Timestamp类型转换
* @param args
* @return
*/
public Timestamp toTimestamp(String args){
Timestamp result = null;
if(null == args || "".equals(args))
result = null;
else
try{
//     result = BigDecimal.parseBigDecimal(args);
result = Timestamp.valueOf(args);
}catch(Exception e){
result = null;
log.error(" // RecordReflection parse Timestamp is error // " + e.getMessage());
}

return result;
}
/**
* 对BigDecimal类型转换
* @param args
* @return
*/
public BigDecimal toBigDecimal(String args){
BigDecimal result = null;
if(null == args || "".equals(args))
result = new BigDecimal(0);
else
try{
//     result = BigDecimal.parseBigDecimal(args);
result = new BigDecimal(args);
}catch(Exception e){
result = new BigDecimal(0);
log.error(" // RecordReflection parse BigDecimal is error // " + e.getMessage());
}

return result;
}
/**
* 对Long类型转换
* @param args
* @return
*/
public Long toLong(String args){
Long result = null;
if(null == args || "".equals(args))
result = new Long(0);
else
try{
result = Long.parseLong(args);
}catch(Exception e){
result = new Long(0);
log.error(" // RecordReflection parse Long is error // " + e.getMessage());
}

return result;
}
/**
* 对Double类型转换
* @param args
* @return
*/
public Double toDouble(String args){
Double result = null;
if(null == args || "".equals(args))
result = new Double(0);
else
try{
result = Double.parseDouble(args);
}catch(Exception e){
result = new Double(0);
log.error(" // RecordReflection parse Double is error // " + e.getMessage());
}

return result;
}
/**
* 对Float类型转换
* @param args
* @return
*/
public Float toFloat(String args){
Float result = null;
if(null == args || "".equals(args))
result = new Float(0);
else
try{
result = Float.parseFloat(args);
}catch(Exception e){
result = new Float(0);
log.error(" // RecordReflection parse Float is error // " + e.getMessage());
}

return result;
}
/**
* 对Integer类型转换
* @param args
* @return
*/
public Integer toInteger(String args){
Integer result = null;
if(null == args || "".equals(args))
result = 0;
else{
try{
result = Integer.parseInt(args);
}catch(Exception e){
result = 0;
log.error(" // RecordReflection parse Integer is error // " + e.getMessage());
}
}
return result;
}
/**
* 对Short类型转换
* @param args
* @return
*/
public Short toShort(String args){
Short result = null;
if(null == args || "".equals(args))
result = 0;
else{
try{
result = Short.parseShort(args);
}catch(Exception e){
result = 0;
log.error(" // RecordReflection parse Short is error // " + e.getMessage());
}
}
return result;
}
/**
* 重写了对String类型的转换
* @param args
* @return
*/
public String toString(String args){
String result = null;
if (null == args || "".equals(args))
result = "";
else
result = args.toString();
return result;
}
}
 

代码片段3(LabelValue 类):

package com.ghrt.frame;
import java.io.Serializable;
public class LabelValue implements Serializable{
private String name;
private String value;
private String type;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息