JDBC 通用的查询方法(能过获取任何的数据库对象):
例如:获取一个Student 对象时(获取的对象不同时,代码会有所不同,但大体相似【下面会讨论通用的查询方法】):
/**
* 查询Student对象 */public class Student {
private int flowid;
private int type; private String idcard; private String examcard; private String studentname; private String location; private int grade;}
通用的查询方法:
ResultSetMetaData:是描述ResultSet 的元数据对象,即从中可以获取到结果集中有多少列,列名是什么
how:1.得到ResultSetMetaData 对象:调用 ResultSet 的 getMetaData()方法 2.ResultSet有哪些方法: int getColumnCount(): SQL 语句中包含哪些列 String getColumnLabel(int column):获取指定的列的列名,其中索引从 1开始
@Test public void testGet(){ String sql = "SELECT flow_id flowid, type, id_card idcard," + " exam_card examcard," + "student_name studentname, location, grade " + "FROM examstudent " + "WHERE flow_id = ?"; Student student = get(Student.class, sql, 7); //System.out.println(sql); System.out.println(student); }
1.先利用 SQL 进行查询,得到结果集2.利用反射创建实体类的对象,创建Student对象3.获取结果集列的别名4.再获取结果集的每一列的值,结合 3 得到一个Map,键:列的别名;值: 列的值。5.再利用反射为 2 的对应的属性赋值:属性即为 Map 的键,值即为Map的值
/** * 通用的查询方法:可以根据传入的 SQL, Class 对象 返回 SQL对应的记录的对象 * @param clazz:描述对象的类型 * @param sql: SQL语句 * @param args:填充占位符的可变参数。 * @return */ public <T> T get(Class<T> clazz, String sql, Object...args){ T entity = null; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = JDBCTools.GetConnection(); preparedStatement = connection.prepareStatement(sql); for(int i = 0; i < args.length; i++){ preparedStatement.setObject(i+1, args[i]); } resultSet = preparedStatement.executeQuery(); Map<String, Object> values= new HashMap<String, Object>(); ResultSetMetaData rsmd = resultSet.getMetaData(); if(resultSet.next()){ for(int i = 0; i < rsmd.getColumnCount(); i++){ String columnLabel = rsmd.getColumnLabel(i + 1); Object columnValue = resultSet.getObject(i + 1); values.put(columnLabel, columnValue); } } if(values.size() > 0){ entity = clazz.newInstance(); for(Map.Entry<String, Object> entry: values.entrySet()){ String fieldName = entry.getKey(); Object fieldValue = entry.getValue(); ReflectionUtils.setFieldValue(entity, fieldName, fieldValue); } } } catch (Exception e) {
e.printStackTrace(); }finally{ JDBCTools.release(resultSet, preparedStatement, connection); } return entity; }
/** * 反射的 Utils 函数集合 * 提供访问私有变量, 获取泛型类型 Class, 提取集合中元素属性等 Utils 函数 * Administrator * */public class ReflectionUtils {
/** * 通过反射, 获得定义 Class 时声明的父类的泛型参数的类型 * 如: public EmployeeDao extends BaseDao<Employee, String> * clazz * index * @return */ @SuppressWarnings("unchecked") public static Class getSuperClassGenricType(Class clazz, int index){ Type genType = clazz.getGenericSuperclass(); if(!(genType instanceof ParameterizedType)){ return Object.class; } Type [] params = ((ParameterizedType)genType).getActualTypeArguments(); if(index >= params.length || index < 0){ return Object.class; } if(!(params[index] instanceof Class)){ return Object.class; } return (Class) params[index]; } /** * 通过反射, 获得 Class 定义中声明的父类的泛型参数类型 * 如: public EmployeeDao extends BaseDao<Employee, String> * @param <T> * @param clazz * @return */ @SuppressWarnings("unchecked") public static<T> Class<T> getSuperGenericType(Class clazz){ return getSuperClassGenricType(clazz, 0); } /** * 循环向上转型, 获取对象的 DeclaredMethod * @param object * @param methodName * @param parameterTypes * @return */ public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes){ for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){ try { //superClass.getMethod(methodName, parameterTypes); return superClass.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { //Method 不在当前类定义, 继续向上转型 } //.. } return null; } /** * 使 filed 变为可访问 * @param field */ public static void makeAccessible(Field field){ if(!Modifier.isPublic(field.getModifiers())){ field.setAccessible(true); } } /** * 循环向上转型, 获取对象的 DeclaredField * @param object * @param filedName * @return */ public static Field getDeclaredField(Object object, String filedName){ for(Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()){ try { return superClass.getDeclaredField(filedName); } catch (NoSuchFieldException e) { //Field 不在当前类定义, 继续向上转型 } } return null; } /** * 直接调用对象方法, 而忽略修饰符(private, protected) * @param object * @param methodName * @param parameterTypes * @param parameters * @return * @throws InvocationTargetException * @throws IllegalArgumentException */ public static Object invokeMethod(Object object, String methodName, Class<?> [] parameterTypes, Object [] parameters) throws InvocationTargetException{ Method method = getDeclaredMethod(object, methodName, parameterTypes); if(method == null){ throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]"); } method.setAccessible(true); try { return method.invoke(object, parameters); } catch(IllegalAccessException e) { System.out.println("不可能抛出的异常"); } return null; } /** * 直接设置对象属性值, 忽略 private/protected 修饰符, 也不经过 setter * @param object * @param fieldName * @param value */ public static void setFieldValue(Object object, String fieldName, Object value){ Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); try { field.set(object, value); } catch (IllegalAccessException e) { System.out.println("不可能抛出的异常"); } } /** * 直接读取对象的属性值, 忽略 private/protected 修饰符, 也不经过 getter * @param object * @param fieldName * @return */ public static Object getFieldValue(Object object, String fieldName){ Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); Object result = null; try { result = field.get(object); } catch (IllegalAccessException e) { System.out.println("不可能抛出的异常"); } return result; }