dbutils中實現數據的增刪改查的方法,反射常用的方法,絕對路徑的寫法(雜記)


jsp的三個指令為:page,include,taglib。。。

 

建立一個jsp文件,建立起絕對路徑,使用時,其他jsp文件導入即可

導入方法:<%@ include file="/commons/common.jsp" %>  (這個jsp文件在根目錄下的commons文件夾下)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<base href="${pageContext.request.scheme }://${pageContext.request.serverName }:${pageContext.request.serverPort }${pageContext.request.contextPath}/">
<!-- 其內容先后為:完全的絕對路徑:http://.... -->

 

反射類:通過反射獲取其他類中的屬性,方法,父類等...

package com.atguigu.bookstore.reflection.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 反射的 Utils 函數集合
 * 提供訪問私有變量, 獲取泛型類型 Class, 提取集合中元素屬性等 Utils 函數
 * @author Administrator
 *
 */
public class ReflectionUtils {

    
    /**
     * 通過反射, 獲得定義 Class 時聲明的父類的泛型參數的類型
     * 如: public EmployeeDao extends BaseDao<Employee, String>
     * @param clazz
     * @param 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;
    }
}

需導入dbutils開源包:commons-dbutils-1.3.

jardbutils方法:實現數據庫數據的增刪改查簡便的方法:

package com.atguigu.bookstore.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.atguigu.bookstore.dao.DAO;
import com.atguigu.bookstore.dbutils.JDBCUtils;
import com.atguigu.bookstore.reflection.utils.ReflectionUtils;
import com.atguigu.bookstore.web.ConnectionContext;

public class BaseDAO<T> implements DAO<T> {
    
    private QueryRunner queryRunner=new QueryRunner();
    
    private Class<T> clazz;
    
    public BaseDAO(){
        //反射類中的反射方法;
        clazz=ReflectionUtils.getSuperGenericType(getClass());
    }
    
    //執行 INSERT 操作, 返回插入后的記錄的 ID,使用QueryRunner不能實現有返回值的操作
    @Override
    public long insert(String sql, Object... args) {
        long id=0;
        
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            connection=ConnectionContext.getInstance().get();
            //Statement.RETURN_GENERATED_KEYS,為返回主鍵
            preparedStatement=connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
            
            if(args!=null){
                for(int i=0;i<args.length;i++){
                    preparedStatement.setObject(i+1, args[i]);
                }
            }
            
            preparedStatement.executeUpdate();
            
            //獲取生成的主鍵值
            resultSet=preparedStatement.getGeneratedKeys();
            if(resultSet.next()){
                id=resultSet.getLong(1);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.release(resultSet, preparedStatement);
        }
        return id;
    }

    @Override
    //執行 UPDATE 操作, 包括 INSERT(但沒有返回值), UPDATE, DELETE
    public void update(String sql, Object... args) {
        Connection connection=null;
        try {
            connection=ConnectionContext.getInstance().get();
            queryRunner.update(connection, sql, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }

    @Override
    //執行單條記錄的查詢操作, 返回與記錄對應的類的一個對象
    public T query(String sql, Object... args) {
        Connection connection=null;
        try {
            connection=ConnectionContext.getInstance().get();
            return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    //執行多條記錄的查詢操作, 返回與記錄對應的類的一個 List
    public List<T> queryForList(String sql, Object... args) {
        Connection connection = null;
        
        try {
            connection = ConnectionContext.getInstance().get();
            return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return null;
    }

    @Override
    //執行一個屬性或值的查詢操作, 例如查詢某一條記錄的一個字段, 或查詢某個統計信息, 返回要查詢的值
    public <V> V getSingleVal(String sql, Object... args) {
        Connection connection=null;
        try {
            connection=ConnectionContext.getInstance().get();
            return (V) queryRunner.query(connection, sql, new ScalarHandler(), args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    //執行批量更新操作
    public void batch(String sql, Object[]... params) {
        Connection connection=null;
        try {
            connection=ConnectionContext.getInstance().get();
            queryRunner.batch(connection, sql, params);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM