程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 基於JDBC封裝的BaseDao(實例代碼)

基於JDBC封裝的BaseDao(實例代碼)

編輯:關於JAVA

基於JDBC封裝的BaseDao(實例代碼)。本站提示廣大學習愛好者:(基於JDBC封裝的BaseDao(實例代碼))文章只能為提供參考,不一定能成為您想要的結果。以下是基於JDBC封裝的BaseDao(實例代碼)正文


比來空閒時萌生寫一寫dao的封裝的例子,就將之前寫的整頓一下。

public class BaseDao<T> {

	Connection conn;
	PreparedStatement st;
	ResultSet rs;
	
	JdbcUtil jdbcUtil = new JdbcUtil();
	
	int result = 0;
	
	private Class<T> persistentClass;
	
	@SuppressWarnings("unchecked")
	public BaseDaoUtil(){		
		conn = jdbcUtil.getConnection();
		ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
		persistentClass = (Class<T>) type.getActualTypeArguments()[0];		
	}
	
	
  /**
   * 保留
    * @param entity
   * @return
   */
	public int save(T entity) throws Exception{
		
		String sql = "INSERT INTO "+ entity.getClass().getSimpleName().toLowerCase() +" (";
		
		List<Method> list = this.matchPojoMethods(entity,"get");
		
		Iterator<Method> iter = list.iterator();
			
		Object obj[] = new Object[list.size()];
		int i = 0;
		//拼接字段次序 insert into table name(id,name,email,
         while(iter.hasNext()) {
            Method method = iter.next();
            sql += method.getName().substring(3).toLowerCase() + ","; 
            if (method.getReturnType().getSimpleName().indexOf("Date") !=-1) {
				SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				obj[i] = sbf.format(method.invoke(entity, new Object[]{}));
		   }else {
				obj[i] = method.invoke(entity, new Object[]{});
		   }     
      i++;
    }
    
    //去失落最初一個,符號insert insert into table name(id,name,email) values(
    sql = sql.substring(0, sql.lastIndexOf(",")) + ") values(";
    
    //拼裝預編譯SQL語句insert insert into table name(id,name,email) values(?,?,?,
    for(int j = 0; j < list.size(); j++) {
    	sql += "?,"; 
    }

    //去失落SQL語句最初一個,符號insert insert into table name(id,name,email) values(?,?,?);
    sql = sql.substring(0, sql.lastIndexOf(",")) + ")";
    
    //到此SQL語句拼接完成,打印SQL語句
    System.out.println(sql);
    
    try {
    	st = conn.prepareStatement(sql);
    	for (int j = 0; j < obj.length; j++) {
				st.setObject(j+1, obj[j]);
			}
			result = st.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
    
		jdbcUtil.getClose(rs, st, conn);
		
		return result;	
	}
	
	/**
	 * 刪除
	 * @param object
	 * @return
	 * @throws SQLException
	 */
	public int deleteId(Object object) throws Exception{
		
		String sql = "delete from "+ persistentClass.getSimpleName().toLowerCase() +" where ";
		
		//經由過程子類的結構函數,取得參數化類型的詳細類型.好比BaseDAO<T>也就是取得T的詳細類型
    T entity = persistentClass.newInstance();
    
    //寄存Pojo(或被操作表)主鍵的辦法對象
    Method idMethod = null;
    
    List<Method> list = this.matchPojoMethods(entity, "set");
    Iterator<Method> iter = list.iterator();
    
    //過濾獲得Method對象
    while(iter.hasNext()) {
      Method tempMethod = iter.next();
      if(tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
        idMethod = tempMethod;
      } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))){
        idMethod = tempMethod;
      }
    }
    //第一個字母轉為小寫
    sql += idMethod.getName().substring(3,4).toLowerCase()+idMethod.getName().substring(4) + " = ?";
    	
		System.out.println(sql);
		
		st = conn.prepareStatement(sql);
		
		//斷定id的類型
    if(object instanceof Integer) {
      st.setInt(1, (Integer)object);
    } else if(object instanceof String){
      st.setString(1, (String)object);
    }
		
		result = st.executeUpdate();
		
		jdbcUtil.getClose(rs, st, conn);
		
		return result;	
	}
	
	/**
	 * 修正
	 * @param entity
	 * @return
	 * @throws Exception
	 */
	public int update(T entity) throws Exception{
		
		String sql = "update "+ entity.getClass().getSimpleName().toLowerCase() +" set ";
		
		List<Method> list = this.matchPojoMethods(entity, "get");
		
		//裝載參數
		Object obj[] = new Object[list.size()];
		int i = 0;
		
		//暫時Method對象,擔任迭代古裝method對象.
    Method tempMethod = null;
    
    //因為修正時不須要修正ID,所以按次序加參數則應當把Id移到最初.
    Method idMethod = null;
    Iterator<Method> iter = list.iterator();
    while(iter.hasNext()) {
      tempMethod = iter.next();
 
      //假如辦法名中帶有ID字符串而且長度為2,則視為ID.
      if(tempMethod.getName().lastIndexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
      	obj[list.size()-1] = tempMethod.invoke(entity, new Object[]{});
        //把ID字段的對象寄存到一個變量中,然後在聚集中刪失落.
        idMethod = tempMethod;
        iter.remove();
      //假如辦法名去失落set/get字符串今後與pojo + "id"想相符(年夜小寫不敏感),則視為ID
      } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))) {
      	obj[list.size()-1] = tempMethod.invoke(entity, new Object[]{});
      	idMethod = tempMethod;
        iter.remove();        
      }
    }
		
    //把迭代指針移到第一名
    iter = list.iterator();
    while(iter.hasNext()) {
      tempMethod = iter.next();
      sql += tempMethod.getName().substring(3).toLowerCase() + "= ?,";
      obj[i] = tempMethod.invoke(entity, new Object[]{});
      i++;
    }
    
    //去失落最初一個,符號
    sql = sql.substring(0,sql.lastIndexOf(","));
    
    //添加前提
    sql += " where " + idMethod.getName().substring(3).toLowerCase() + " = ?";
    
    //SQL拼接完成,打印SQL語句
    System.out.println(sql);
		
    st = conn.prepareStatement(sql);
    
    for (int j = 0; j < obj.length; j++) {
			st.setObject(j+1, obj[j]);
		}
    
    result = st.executeUpdate();

    jdbcUtil.getClose(rs, st, conn);
    
		return result;

	}
	
	
	public T findById(Object object) throws Exception{
		
		String sql = "select * from "+ persistentClass.getSimpleName().toLowerCase() +" where ";
		
		//經由過程子類的結構函數,取得參數化類型的詳細類型.好比BaseDAO<T>也就是取得T的詳細類型
    T entity = persistentClass.newInstance();
    
    //寄存Pojo(或被操作表)主鍵的辦法對象
    Method idMethod = null;
    
    List<Method> list = this.matchPojoMethods(entity, "set");
    Iterator<Method> iter = list.iterator();
    
    //過濾獲得Method對象
    while(iter.hasNext()) {
      Method tempMethod = iter.next();
      if(tempMethod.getName().indexOf("Id") != -1 && tempMethod.getName().substring(3).length() == 2) {
        idMethod = tempMethod;
      } else if((entity.getClass().getSimpleName() + "Id").equalsIgnoreCase(tempMethod.getName().substring(3))){
        idMethod = tempMethod;
      }
    }
    //第一個字母轉為小寫
    sql += idMethod.getName().substring(3,4).toLowerCase()+idMethod.getName().substring(4) + " = ?";
    	
		System.out.println(sql);
		
		st = conn.prepareStatement(sql);
		
		//斷定id的類型
    if(object instanceof Integer) {
      st.setInt(1, (Integer)object);
    } else if(object instanceof String){
      st.setString(1, (String)object);
    }
		
    rs = st.executeQuery();
        
    //把指針指向迭代器第一行
    iter = list.iterator();
    
    //封裝
    while(rs.next()) {
      while(iter.hasNext()) {
        Method method = iter.next();
        if(method.getParameterTypes()[0].getSimpleName().indexOf("String") != -1) {
          //因為list聚集中,method對象掏出的辦法次序與數據庫字段次序紛歧致(好比:list的第一個辦法是setDate,而數據庫按次序取的是"123"值)
          //所以數據庫字段采取名字對應的方法取.
          this.setString(method, entity, rs.getString(method.getName().substring(3).toLowerCase()));
        } else if(method.getParameterTypes()[0].getSimpleName().indexOf("Date") != -1){
          this.setDate(method, entity, rs.getDate(method.getName().substring(3).toLowerCase()));
        }else {
          this.setInt(method, entity, rs.getInt(method.getName().substring(3).toLowerCase()));
        }  
      }
    }
		
    jdbcUtil.getClose(rs, st, conn);
    
		return entity;
		
	}
	
	
	
	
	
	/**
   * 過濾以後Pojo類一切帶傳入字符串的Method對象,前往List聚集.
   */
  private List<Method> matchPojoMethods(T entity,String methodName) {
    //取得以後Pojo一切辦法對象
    Method[] methods = entity.getClass().getDeclaredMethods();
    
    //List容器寄存一切帶get字符串的Method對象
    List<Method> list = new ArrayList<Method>();
    
    //過濾以後Pojo類一切帶get字符串的Method對象,存入List容器
    for(int index = 0; index < methods.length; index++) {
      if(methods[index].getName().indexOf(methodName) != -1) {
        list.add(methods[index]);
      }
    }    
    return list;
  }
  

  /**
   * 參數類型為String時,為entity字段設置參數,對應set
   */
  public String setString(Method method, T entity, String arg) throws Exception{
    return (String)method.invoke(entity, new Object[]{arg});
  }
  
  
  /**
   * 參數類型為Date時,為entity字段設置參數,對應set
   */
  public Date setDate(Method method, T entity, Date arg) throws Exception{
    return (Date)method.invoke(entity, new Object[]{arg});
  }
	
	
  /**
   * 參數類型為Integer或int時,為entity字段設置參數,對應set
   */
  public Integer setInt(Method method, T entity, Integer arg) throws Exception{
    return (Integer)method.invoke(entity, new Object[]{arg});
  }
 	
}

以上這篇基於JDBC封裝的BaseDao(實例代碼)就是小編分享給年夜家的全體內容了,願望能給年夜家一個參考,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved