將ResultSet對象填充實體bean

package com.neusoft.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

import bamboo.DivisionInvVO;

public class ResultToBean<T> {
 private T obj;
 
 public ResultToBean(){
  
 }
 
 public ResultToBean(T t){
  this.obj=t;
 }
 public static void main(String [] args){
  ResultToBean<DivisionInvVO> bean=new ResultToBean<DivisionInvVO>(new DivisionInvVO());
  try {
   Connection con=DBUtil.getConnection("69");
   ResultSet rs=con.prepareStatement(" select t.* from DIVISION_INV t ").executeQuery();
      List<DivisionInvVO> vos=bean.getBean(rs);
      System.out.println(vos.size());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public List<T> getBean(ResultSet rs) throws Exception{
  List<T> objs=new ArrayList<T>();
  Object[] arg=new Object[1];
  Method method=null;
  Field field=null;
  String fieldType=null;
  ResultSetMetaData meta=rs.getMetaData();
  while(rs.next()){

  obj=(T) Class.forName(obj.getClass().getName()).newInstance();
   for(int i=1;i<=meta.getColumnCount();i++){
    String fieldName=meta.getColumnName(i).toLowerCase();
    String fieldMethod = "set"
     + fieldName.substring(0, 1).toUpperCase()
     + fieldName.substring(1);
    field=obj.getClass().getDeclaredField(fieldName);
    method = obj.getClass().getMethod(fieldMethod,
      new Class[] { field.getType() });
    fieldType=field.getType().getName();
    if(fieldType.equals("int")||fieldType.equals("Integer")){
       arg= new Integer[]{rs.getInt(i)}; 
       method.invoke(obj, arg );
    }else{
     arg = new Object[]{ rs.getObject(i) };
     method.invoke(obj, arg );
    }
   }
   objs.add(obj);
  }
  return objs;
 }

 public T getObj() {
  return obj;
 }

 public void setObj(T obj) {
  this.obj = obj;
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章