当前位置: 代码迷 >> Java相关 >> 来调在QueryRunner中的应用(45)
  详细解决方案

来调在QueryRunner中的应用(45)

热度:293   发布时间:2016-04-22 20:20:04.0
回调在QueryRunner中的应用(45)

第一步:实现一个调用类:

    /**

     * 有回调的查询

     */

    public <T> T query(String sql,MyHandler<T> mh){

       T t = null;

       //声明conn

       Connection con = null;

       try{

           con = ds.getConnection();

           //执行查询

           Statement st = con.createStatement();

           ResultSet rs = st.executeQuery(sql);

           //让回调去执行数据封装

           t = mh.handler(rs);

       }catch(Exception e){

           e.printStackTrace();

       }finally{

           try {

              con.close();

           } catch (SQLException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

           }

       }

       return t;

    }

 

第二步:定义回调规范

package cn.itcast.dbutils;

 

import java.sql.ResultSet;

/**

 * 接收rs结果集

 * @author Administrator

 *

 * @param <T>

 */

public interface MyHandler<T> {

    T handler(ResultSet rs);

}

 

第三步:实现一个回调

package cn.itcast.dbutils;

 

import java.lang.reflect.Method;

import java.sql.ResultSet;

import java.sql.ResultSetMetaData;

import java.util.ArrayList;

import java.util.List;

 

public class MyBeanListHandler<T> implements MyHandler<List<T>> {

    private Class<T> cls;

    public MyBeanListHandler(Class<T> cls) {

       this.cls=cls;

    }

    public List<T> handler(ResultSet rs) {

       List<T> list = new ArrayList<T>();

       try{

           ResultSetMetaData rsmd = rs.getMetaData();

           int cols = rsmd.getColumnCount();

           while(rs.next()){

              T t = cls.newInstance();

              //获取列名

              for(int i=0;i<cols;i++){

                  String colName = rsmd.getColumnName(i+1);

                  String methodName =

                         "set"+colName.substring(0,1)

                         .toUpperCase()

                         +colName.substring(1).toLowerCase();

                  //获取类型

                  String javaType = rsmd.getColumnClassName(i+1);//="java.lang.String";

                  try{

                     Method mm =

                            cls.getMethod(methodName, Class.forName(javaType));

                    Object val = rs.getObject(i+1);

                     mm.invoke(t,val);

                  }catch(Exception e){}

              }

              list.add(t);

           }

       }catch (Exception e) {

       }

       return list;

    }

}

 

第四步:测试:

@Test

    public void myutils3(){

       QueryRunner run = new QueryRunner(DataSourceUtils.getDatasSource());

       String sql = "select * from users";

       List<User> cs =

              run.query(sql,new MyBeanListHandler<User>(User.class));

       for(User c:cs){

           System.err.println(">>:"+c);

       }

    }