结果集处理器的实现

结果集处理器

装饰类的使用:

wrapper是一个接口类: 
The wrapper pattern is employed by many JDBC driver
多被应用于JDBC驱动器的加载
The wrapper pattern is employed by many JDBC driver implementations to provide extensions beyond the traditional JDBC API that are specific to a data source. Developers may wish to gain access to these resources that are wrapped (the delegates) as proxy class instances representing the the actual resources. This interface describes a standard mechanism to access these wrapped resources represented by their proxy, to permit direct access to the resource delegates.

接口和接口之间通过继承来增强父类的接口,而不需重写父类的方法
就如同
ResultSetMetaData继承Wrapper一样

ResultSetMetaData接口:

An object that can be used to get information about the types and properties of the columns in a ResultSet object. The following code fragment creates the ResultSet object rs, creates the ResultSetMetaData object rsmd, and uses rsmd to find out how many columns rs has and whether the first column in rs can be used in a WHERE clause.

BeanInfo接口:

用来处理javaBean对象的属性和参数
Use the BeanInfo interface to create a BeanInfo class and provide explicit information about the methods, properties, events, and other features of your beans.

Introspector类:

是一个工具类用来获取一个javaBean对象的具体属性和参数
The Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean.

结果处理器的实现:

步骤一:创建结果集处理器接口

package JDBCTemp;

import java.sql.ResultSet;

public interface ResultHandler<T> {
    T Handler(ResultSet rs);
}

步骤二:实现结果集处理器;(用于javaBean对象的封装)

方式一:集合数据的封装
package JDBCTemp.Imp;
import JDBCTemp.ResultHandler;
import java.beans.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ResultHandlerImpl<T>  implements ResultHandler {
    //定义一个构造方法用来传入javaBean的类
    Class cl;
    public ResultHandlerImpl(Class cl) {
        this.cl = cl;
    }
    @Override
    public T Handler(ResultSet rs) {
        List<T> list = new ArrayList<T>();
        try {
            //获取结果集的具体信息
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            //获取表中字段的个数
            int columnCount = resultSetMetaData.getColumnCount();
            //获取javaBean对象的具体属性信息
            BeanInfo beanInfo = Introspector.getBeanInfo(cl);
            //获取表中各属性的名称集
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            //对结果集进行判断并进行javaBean和表中字段的映射
            //使用反射获取javaBean对象
            while(rs.next()){
                //每次循环创建一个bean对象
                Object bean = cl.newInstance();
                for (int i =1; i <=columnCount; i++) {
                    //获取表中每个字段的具体属性名称和类型
                    String columnName = resultSetMetaData.getColumnName(i);
                    String columnClassNames = resultSetMetaData.getColumnClassName(i);
                    //对获取到的类型路径进行处理
                    //方式一:
                    String[] cmts = columnClassNames.split("\\.");
                    String columnClassName = cmts[2];
                    //方式二:
                    String cmtss = columnClassNames.substring(columnClassNames.lastIndexOf(".")+1);
                    //以上两种皆可截取字符串
                    //遍历javaBean对象来进行具体判断并进行封装
                    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                        if(propertyDescriptor.getPropertyType().getSimpleName().equals(cmtss)&&propertyDescriptor.getName().equals(columnName)){
                            //准备封装
                            //将表中数据取出
                            Object rsMetaData = rs.getObject(columnName);
                            Method writeMethod = propertyDescriptor.getWriteMethod();
                            writeMethod.invoke(bean,rsMetaData);
                        }
                    }
                }
                list.add((T)bean);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        return  (T)list;
    }
}
方式二:一个参数的封装
public class HandlerOne<T> implements ResultHandler {
    Class cl;

    public HandlerOne(Class cl) {
        this.cl = cl;
    }

    public T Handler(ResultSet rs) {
        Object bean = null;
        try {
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();

            BeanInfo beanInfo = Introspector.getBeanInfo(cl);
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();

            while (rs.next()) {
                bean = cl.newInstance();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    String columnClassName = metaData.getColumnClassName(i);
                    String[] split = columnClassName.split("\\.");
                    String name = split[2];
                    for (PropertyDescriptor pd : pds) {
                        if (pd.getName().equals(columnName) && pd.getPropertyType().getSimpleName().equals(name)) {
                            Object data = rs.getObject(columnName);
                            Method writeMethod = pd.getWriteMethod();
                            writeMethod.invoke(bean, data);
                        }
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IntrospectionException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return (T) bean;
    }
}

步骤三:sql语句执行工具,(进行sql语句的参数封装)

package JDBCTemp;
import JDBCTemp.Utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Temp<T> {
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
//构建方法用于参数匹配
    public T selectOne(String sql, ResultHandler handler, Object... parames) {
        Object bean = null;
        try {
            //获取连接对象
            conn = JDBCUtils.getCon();
            ps = conn.prepareStatement(sql);
            //获取参数的个数
            int parameterCount = ps.getParameterMetaData().getParameterCount();
            if (parameterCount != parames.length) {
                throw new RuntimeException("参数不匹配");
            }
            //将参数进行封装
            for (int i = 1; i <= parameterCount; i++) {
                ps.setObject(i, parames[i - 1]);
            }
            rs = ps.executeQuery();
            bean = handler.Handler(rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return (T) bean;
    }
    public T selectList(String sql, ResultHandler handler, Object... parames) {
        List<T> list = new ArrayList<>();
        try {
            conn = JDBCUtils.getCon();
            ps = conn.prepareStatement(sql);
            int parameterCount = ps.getParameterMetaData().getParameterCount();
            if (parameterCount != parames.length) {
                throw new RuntimeException("参数不匹配");
            }
            for (int i = 1; i <= parameterCount; i++) {
                ps.setObject(i, parames[i - 1]);
            }
            rs = ps.executeQuery();
            list = (List<T>) handler.Handler(rs);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return (T) list;
    }

    public int updates(String sql, Object... parames){
        int count  = 0;
        try {
            conn = JDBCUtils.getCon();
            ps = conn.prepareStatement(sql);
            int parameterCount = ps.getParameterMetaData().getParameterCount();
            if (parameterCount != parames.length) {
                throw new RuntimeException("参数不匹配");
            }
            for (int i = 1; i <= parameterCount; i++) {
                ps.setObject(i, parames[i - 1]);
            }
            count = ps.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

}

步骤四:进行sql语句的定义返回封装的JavaBean对象

    //返回一个对象的测试类
package JDBCTemp;
import JDBCTemp.Imp.HandlerOne;
import JDBCTemp.entity.Student;
public class Test {
    public static void main(String[] args) {
        String sql = "select * from user_table where user_id = ?";
        Temp<Student> temp = new Temp<>();
       Student student = temp.selectOne(sql,new HandlerOne(Student.class),1);
        System.out.println(student);
    }
}
    //返回对象集合的测试类
package JDBCTemp;
import JDBCTemp.Imp.ResultHandlerImpl;
import JDBCTemp.entity.Student;
import java.util.List;
public class Test2 {
    public static void main(String[] args) {
        int i =1;
        String sql = "select * from user_table ";
        Temp<Student> temp = new Temp<>();
        List<Student> students = (List<Student>)temp.selectList(sql,new ResultHandlerImpl(Student.class));
        for (Student student : students) {
            System.out.println(i++);
            System.out.println(student);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雨中修行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值