我自己的数据对象处理类 BaseDAO

package com.jh.core.db.jdbc;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;


import com.jh.core.util.JHPage;

/**
 * Created by IntelliJ IDEA. User: wanglch Date: 2005-6-15 Time: 9:48:20
 * 通用DAO数据处理类 辅助完成数据的相关的装载更新的操作 自行管理数据库联接类
 */
abstract public class BaseDAO<T> {
 public  abstract String getDBName();
 private Class clazz = null;

 static Logger log = Logger.getLogger(BaseDAO.class);

 // 获得结果集中数据的拷贝对象一个
 // RsInfo rsInfo=new RsInfo(rs);

 protected BaseDAO(Class<T> clazz) {
  this.clazz = clazz;
 }

 /**
  * 获得结果集中数据的拷贝对象一个 RsInfo rsInfo=new RsInfo(rs);
  *
  * @param rs
  *            结果集
  * @param rsInfo
  *            该对象辅助sql对象装载工具
  * @return 返回具体对象
  * @throws Exception
  */

 @SuppressWarnings("unchecked")
 static private Object rs2Bean(java.sql.ResultSet rs, RsInfo rsInfo)
   throws Exception {
  if(String.class.equals(rsInfo.clazz)){
   return rs.getString(1);
  }
  if(long.class.equals(rsInfo.clazz)){
   return rs.getLong(1);
  }
  if(Long.class.equals(rsInfo.clazz)){
   return rs.getLong(1);
  }
  if(int.class.equals(rsInfo.clazz)){
   return rs.getInt(1);
  }
  if(Integer.class.equals(rsInfo.clazz)){
   return rs.getInt(1);
  }
  Object obj = rsInfo.clazz.newInstance();
       
  try {
   List<LoadRs2P> list = rsInfo.getList();
   for (LoadRs2P lrp : list)
    lrp.set(rs, obj);
  } catch (Exception e) {
   e.printStackTrace();
  }
  return obj;
 }

 // 获得sql数据的拷贝对象

 /**
  * 获得一个对象 sql 查询到一个对象的装载过程实现
  *
  * @param sql
  * @param clazz
  * @return 具体的类的实例
  * @throws Exception
  */
 @SuppressWarnings("unchecked")
  public T getObj( final String sql) throws Exception {
  return (T) DBUtil.execute(getDBName(), new DBCallBack() {
   public Object execute(Connection conn) throws Exception {
    Statement stmt = conn.createStatement();
    log.debug("\n开始执行查询[ " + sql + " ] 嘿咻嘿咻 ");
    ResultSet rs = stmt.executeQuery(sql);
    RsInfo rsInfo = null;
    if (rs.next()) {
     rsInfo = new RsInfo(rs, clazz);
     return (T) rs2Bean(rs, rsInfo);
    }
    return null;
   }
  });
 }

 protected static Object getObj(String dbName, final String sql,
   final Class clazz0) throws Exception {
  return DBUtil.execute(dbName, new DBCallBack() {

   public Object execute(Connection conn) throws Exception {
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
    if (rs.next()) {
     RsInfo rsInfo = new RsInfo(rs, clazz0);
     return rs2Bean(rs, rsInfo);
    }
    return null;
   }
  });
 }
 public List<T> getObjList( final String sql,String countSql, JHPage page)
 throws Exception {
  page.setCount(BaseDAO.getIValue(getDBName(), countSql));
  List<T> list = getObjList( sql + " limit " + page.getStart() + " ,"
  + page.getSize());
  page.setList(list);
  return list;
 }
 public List<T> getObjList( final String sql, JHPage page)
   throws Exception {
  return getObjList(sql,"select count(1) from ( " + sql+ " ) as c",page);
 }

 public List<T> getObjList( final String sql, int limit)
   throws Exception {
  return getObjList( sql + " limit " + limit);
  
 }

 @SuppressWarnings("unchecked")
 public List<T> getObjList( final String sql)
   throws Exception {
  log.debug("\n  getObjectList sql = " + sql + "");
  return (List<T>) DBUtil.execute(getDBName(), new DBCallBack() {
   public Object execute(Connection conn) throws Exception {
    List<T> list = new ArrayList();
    Statement pstmt = conn.createStatement();
    ResultSet rs = pstmt.executeQuery(sql);
    RsInfo<T> rsInfo = null;
    if (rs.next()) {
     rsInfo = new RsInfo<T>(rs, clazz);
     list.add((T) rs2Bean(rs, rsInfo));
    }
    while (rs.next()) {
     list.add((T) rs2Bean(rs, rsInfo));
    }
    return list;
   }

  });

 }
 protected static List getObjList(String dbName, final String sql, String countSql,
   final Class clazz0, JHPage page) throws Exception {
  page.setCount(BaseDAO.getIValue(dbName, countSql));
  List list = getObjList(dbName, sql + " limit " + page.getStart() + " ,"
    + page.getSize(), clazz0);
  page.setList(list);
  return list;
  
 }
 protected static List getObjList(String dbName, final String sql,
  final Class clazz0, JHPage page) throws Exception {
  return getObjList(dbName,sql,"select count(1) from ( " + sql+ " ) as c",clazz0,page);
 }

 protected static List getObjList(String dbName, final String sql,
   final Class clazz0) throws Exception {
  log.debug("\n  getObjectList sql = " + sql + "");
  return (List) DBUtil.execute(dbName, new DBCallBack() {
   @SuppressWarnings("unchecked")
   public Object execute(Connection conn) throws Exception {
    List list = new ArrayList();
    Statement pstmt = conn.createStatement();
    ResultSet rs = pstmt.executeQuery(sql);
    RsInfo rsInfo = null;
    if (rs.next()) {
     rsInfo = new RsInfo(rs, clazz0);
     list.add(rs2Bean(rs, rsInfo));
    }
    while (rs.next()) {
     list.add(rs2Bean(rs, rsInfo));
    }
    return list;
   }

  });

 }

 public static List getMapList(String dbName, final String sql)
   throws Exception {
  log.debug("\n  getObjectList sql = " + sql + "");
  return (List) DBUtil.execute(dbName, new DBCallBack() {
   public Object execute(Connection conn) throws Exception {
    List<Map<?, ?>> list = new ArrayList<Map<?, ?>>();
    Statement pstmt = conn.createStatement();
    ResultSet rs = pstmt.executeQuery(sql);

    while (rs.next()) {
     list.add(rs2Map(rs));
    }
    return list;
   }
  });
 }

 public static Map getMapObj(String dbName, final String sql)
   throws Exception {
  log.debug("\n  getObjectList sql = " + sql + "");
  return (Map) DBUtil.execute(dbName, new DBCallBack() {
   public Object execute(Connection conn) throws Exception {
    Statement pstmt = conn.createStatement();
    ResultSet rs = pstmt.executeQuery(sql);

    if (rs.next()) {
     return (rs2Map(rs));
    }
    return null;
   }
  });
 }

 @SuppressWarnings("unchecked")
 static private Map rs2Map(ResultSet rs) {
  try {
   Map map = new HashMap();
   ResultSetMetaData m = rs.getMetaData();
   for (int i = 0; i < m.getColumnCount(); i++) {
    // System.out.println(m.getColumnName(i+1)+"="+rs.getString(i+1));
    if ("java.sql.Timestamp".equals(m.getColumnClassName(i + 1))) {
     try {
      map.put(m.getColumnName(i + 1), new java.util.Date(rs
        .getTimestamp(i + 1).getTime()));
     } catch (Exception e) {
     }
    } else {
     if(rs.getString(i + 1)==null||rs.getString(i + 1).equals("null")){
      map.put(m.getColumnName(i + 1), "0" );
     }else{
      map.put(m.getColumnName(i + 1), "" + rs.getString(i + 1));
     }
     
    }
   }
   return map;
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return null;
 }

 // 把对象中的数据形成sql语句段

 /**
  * 通过对象,字段名字 获得相关的数据库所需要的值类型
  *
  * @param str
  * @param obj
  * @return 返回对应数据库的相应代码。
  */
 private static String getSqlValue(String str, Object obj) {
  Class clazz = obj.getClass();
  Field field = null;
  try {
   field = clazz.getDeclaredField(str);
   field.setAccessible(true);
   if (field.getType().equals(String.class)) {
    String value = (String) (field.get(obj));
    if ("".equals(value) || value == null)
     value = "";
    // value = value.replaceAll("'", "''");
    // value = value.replaceAll("\"", "&quot;");
    return "" + value + "";

   } else if (field.getType().equals(Date.class)) {
    String dateStr = UtilTime.getDateToString(
      (Date) field.get(obj), "yyyy-MM-dd HH:mm:ss");
    if (dateStr != null)
     return "" + dateStr + "";
   } else if (field.getType().equals(int.class)) {
    return "" + field.get(obj) + "";
   } else {
    return "" + field.get(obj) + "";
   }
  } catch (NoSuchFieldException e) {
   log.debug("对象中没有找到相应的列:" + e);
   return "''";
  } catch (Exception e) {
   return "''";
  }
  return "''";
 }
 private static java.sql.Timestamp getSqlDateValue(String str, Object obj) {
  Class clazz = obj.getClass();
  Field field = null;
  try {
   field = clazz.getDeclaredField(str);
   field.setAccessible(true);
     if (field.getType().equals(Date.class)) {
    
     java.util.Date date=(java.util.Date) field.get(obj);
      if(date==null)return new  java.sql.Timestamp(new Date().getTime());  
     return new  java.sql.Timestamp(date.getTime());
     }
  } catch (NoSuchFieldException e) {
   log.debug("对象中没有找到相应的列:" + e);
   return null;
  } catch (Exception e) {
   return null;
  }
  return null;
 }
 private static String genPUpdateSql(String tableName, String[] columnName,
   String[] whereColumn) {
  StringBuffer buff = new StringBuffer();

  buff.append(" update   ");
  buff.append(" " + tableName + " set ");
  buff.append(columnName[0] + "= ? ");
  for (int i = 1; i < columnName.length; i++) {
   buff.append(", " + columnName[i]);
   buff.append("= ? ");
  }
  buff.append(" where 1=1 ");
  for (int i = 0; whereColumn != null && i < whereColumn.length; i++) {
   buff.append(" and " + whereColumn[i]);
   buff.append("= ? ");
  }
  return buff.toString();
 }

 /**
  * 预编译更新
  *
  * @param tableName
  * @param columnName
  * @param whereColumn
  * @param obj
  */
 protected static void updateObj(String dbName, String tableName,
   final String[] columnName, final String[] whereColumn,
   final Object obj) {

  PreparedDBCallBack pcallBack = new PreparedDBCallBack() {
   @Override
   public Object execute(PreparedStatement ps) throws SQLException {
    int k = 1;
    StringBuffer s = new StringBuffer();
    for (int i = 0; columnName != null && i < columnName.length; i++) {
     if(isDateTime(columnName[i], obj)){
        Timestamp dateSql=getSqlDateValue(columnName[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
     }else{
       String str = getSqlValue(columnName[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

     }
     k++;
    }
    for (int i = 0; whereColumn != null && i < whereColumn.length; i++) {
     if(isDateTime(whereColumn[i], obj)){
        Timestamp dateSql=getSqlDateValue(whereColumn[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
     }else{
       String str = getSqlValue(whereColumn[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

     }
     k++;
    }
    log.debug(s.toString());
    return ps.execute();
   }
  };

  String sql = genPUpdateSql(tableName, columnName, whereColumn);
  log.debug("\n开始执行 sql=  " + sql);
  DBUtil.preparedExecute(dbName, pcallBack, sql);
 }
 
 protected static void updateObj(String dbName, String tableName,
   final String[] columnName, final String[] whereColumn,
   final List list) {

  PreparedDBCallBack pcallBack = new PreparedDBCallBack() {
   @Override
   public Object execute(PreparedStatement ps) throws SQLException {
    
    StringBuffer s = new StringBuffer();
    for(Object obj:list){
     int k = 1;
    for (int i = 0; columnName != null && i < columnName.length; i++) {
     if(isDateTime(columnName[i], obj)){
        Timestamp dateSql=getSqlDateValue(columnName[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
     }else{
       String str = getSqlValue(columnName[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

     }
     k++;
    }
    for (int i = 0; whereColumn != null && i < whereColumn.length; i++) {
     if(isDateTime(whereColumn[i], obj)){
        Timestamp dateSql=getSqlDateValue(whereColumn[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
     }else{
       String str = getSqlValue(whereColumn[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

     }
     k++;
    }
    s.append("\n#---------------------------#");
    ps.addBatch();
    }
    log.debug(s.toString());
    return ps.executeBatch();
   }
  };

  String sql = genPUpdateSql(tableName, columnName, whereColumn);
  log.debug("\n开始执行 sql=  " + sql);
  DBUtil.preparedExecute(dbName, pcallBack, sql);
 }
 protected static void updateObj(String dbName, String tableName,
   final String[] columnName, final String where, final Object obj) {

  PreparedDBCallBack pcallBack = new PreparedDBCallBack() {
   @Override
   public Object execute(PreparedStatement ps) throws SQLException {
    int k = 1;
    StringBuffer s = new StringBuffer();
    for (int i = 0; i < columnName.length; i++) {
     if(isDateTime(columnName[i], obj)){
        Timestamp dateSql=getSqlDateValue(columnName[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
     }else{
       String str = getSqlValue(columnName[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

     }
     k++;
    }

    return ps.execute();
   }
  };

  String sql = genPUpdateSql(tableName, columnName, null) + " and "
    + where;
  DBUtil.preparedExecute(dbName, pcallBack, sql);
 }
 protected static void updateObj(String dbName, String tableName,
   final String[] columnName, final String where, final List list) {

  PreparedDBCallBack pcallBack = new PreparedDBCallBack() {
   @Override
   public Object execute(PreparedStatement ps) throws SQLException {
    StringBuffer s = new StringBuffer();
    for (Object obj:list){
    int k = 1;
    for (int i = 0; i < columnName.length; i++) {
     if(isDateTime(columnName[i], obj)){
        Timestamp dateSql=getSqlDateValue(columnName[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
      }else{
       String str = getSqlValue(columnName[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

      }
     k++;
    }
    ps.addBatch();
    }
    log.debug(s.toString());
    
    return ps.executeBatch();
   }
  };

  String sql = genPUpdateSql(tableName, columnName, null) + " and "
    + where;
  DBUtil.preparedExecute(dbName, pcallBack, sql);
 }

 
 static private boolean isDateTime(String columnName, Object obj){
  Class clazz = obj.getClass();
 
  try {
   Field
   field = clazz.getDeclaredField(columnName);
   if(field.getType().equals(java.util.Date.class)){
    return true;
   }
  }catch(Exception e){
   
  }
  return false;
 }
 /**
  * 预编译增加
  *
  * @param tableName
  * @param columnName
  * @param obj
  */
 protected static long insertObj(String dbName, String tableName,
   final String[] columnName, final Object obj) {
  PreparedDBCallBack pcallBack = new PreparedDBCallBack() {
   @Override
   public Object execute(PreparedStatement ps) throws SQLException {
    int k = 1;
    StringBuffer s = new StringBuffer();
    for (int i = 0; i < columnName.length; i++) {
     if(isDateTime(columnName[i], obj)){
       Timestamp dateSql=getSqlDateValue(columnName[i], obj);
       ps.setTimestamp(k, dateSql);
       s.append("\n参数" + k + "=  " + dateSql);
     }else{
      String str = getSqlValue(columnName[i], obj);
      s.append("\n参数" + k + "=  " + str);
      ps.setString(k, str);

     }
     // System.out.println(k);
     k++;
    }
    log.debug(s.toString());
    ps.execute();
    String sql="select LAST_INSERT_ID()";
       java.sql.ResultSet rs= ps.executeQuery(sql);
    if(rs.next()){
     return rs.getLong(1);
    }
    return new Long(0) ;
   }
  };

  String sql = genPInsertSql(tableName, columnName);
  log.debug("\n psql=" + sql);
  // System.out.println("psql=" + sql);
  return (Long)DBUtil.preparedExecute(dbName, pcallBack, sql);
 }
 protected static void insertObjList(String dbName, String tableName,
   final String[] columnName, final List list) {
  PreparedDBCallBack pcallBack = new PreparedDBCallBack() {
   @Override
   public Object execute(PreparedStatement ps) throws SQLException {
    StringBuffer s = new StringBuffer();
    for(Object obj: list) {
    int k = 1;
    
    
    for (int i = 0; i < columnName.length; i++) {
     if(isDateTime(columnName[i], obj)){
        Timestamp dateSql=getSqlDateValue(columnName[i], obj);
        ps.setTimestamp(k, dateSql);
        s.append("\n参数" + k + "=  " + dateSql);
     }else{
       String str = getSqlValue(columnName[i], obj);
       s.append("\n参数" + k + "=  " + str);
       ps.setString(k, str);

     }
     k++;
    }
    s.append("\n#####################################\n");
    ps.addBatch();
    
    }
    ps.executeBatch();
    log.debug(s.toString());
    return null;
   }
  };

  String sql = genPInsertSql(tableName, columnName);
  log.debug("\n psql=" + sql);
  // System.out.println("psql=" + sql);
  DBUtil.preparedExecute(dbName, pcallBack, sql);
 }

 private static String genPInsertSql(String tableName, String[] columnName) {
  StringBuffer buff = new StringBuffer();
  StringBuffer buff2 = new StringBuffer();
  buff.append(" insert into  ");
  buff.append(" " + tableName + "(");
  buff.append(columnName[0]);
  buff2.append(" ? ");
  for (int i = 1; i < columnName.length; i++) {
   buff.append(", " + columnName[i]);
   buff2.append(",? ");
  }
  buff.append(") values (");
  buff.append(buff2.toString());
  buff.append(")");
  return buff.toString();
 }

 /**
  * 取值特定统计或者查询方法 <br>
  * 该查询不检查查询的合法性
  *
  * @param sql
  * @return
  * @throws Exception
  */
 public static Object getValue(String dbName, final String sql)
   throws Exception {
  log.debug("\n  getPObjects sql = " + sql + "");
  return (Object) DBUtil.execute(dbName, new DBCallBack() {
   public Object execute(Connection conn) throws Exception {
    Statement pstmt = conn.createStatement();
    ResultSet rs = pstmt.executeQuery(sql);
    if (rs.next()) {
     return rs.getObject(1);
    }
    return null;
   }
  });
 }
 public static int getIValue(String dbName, final String sql)
 throws Exception {
 return (Integer) DBUtil.execute(dbName, new DBCallBack() {
 public Object execute(Connection conn) throws Exception {
  Statement pstmt = conn.createStatement();
  ResultSet rs = pstmt.executeQuery(sql);
  if (rs.next()) {
   return rs.getInt(1);
  }
  return 0;
 }
});
}
 public static long getLValue(String dbName, final String sql)
 throws Exception {
 return (Long) DBUtil.execute(dbName, new DBCallBack() {
 public Object execute(Connection conn) throws Exception {
  Statement pstmt = conn.createStatement();
  ResultSet rs = pstmt.executeQuery(sql);
  if (rs.next()) {
   return rs.getLong(1);
  }
  return 0l;
 }
});
}
 /**
  * 执行更新
  *
  * @param sql
  * @return 返回执行执行状态
  * @throws SQLException
  */
 protected static boolean execute(String dbName, String sql)
   throws SQLException {
  log.debug("sql=" + sql);
  Connection conn = null;
  try {
   conn = DBConnection.getDBConnection(dbName);
   Statement stmt = conn.createStatement();
   try {
    return stmt.execute(sql);
   } finally {
    // stmt.close();
   }
  } finally {
   conn.close();
  }

 }

 /**
  * 批处理更新并返回每个批次的更新结果
  *
  * @param sqlList
  * @return 每个批次的更新结果
  * @throws SQLException
  */
 public static int[] update(String dbName, List sqlList)
   throws SQLException {
     
  Connection conn = null;
  try {
   conn = DBConnection.getDBConnection(dbName);
   Statement stmt = conn.createStatement();
   try {
    Iterator it = sqlList.iterator();
    while (it.hasNext()) {
     stmt.addBatch((String) it.next());
    }
    return stmt.executeBatch();
   } finally {
    stmt.close();
   }
  } finally {
   conn.close();
  }

 }

 /**
  * 执行更新
  *
  * @param sql
  * @return 更新数量
  * @throws SQLException
  */
 public static int update(String dbName, String sql) throws SQLException {
  log.debug("updateSql=" + sql);
  Connection conn = null;
  try {
   conn = DBConnection.getDBConnection(dbName);
   Statement stmt = conn.createStatement();
   try {
    return stmt.executeUpdate(sql);
   } finally {
    stmt.close();
   }
  } finally {
   conn.close();
  }
 }

 /**
  * 获得有限条数的对象list
  *
  * @param db_name
  * @param sql
  * @param clazz0
  * @param limit
  * @return
  * @throws Exception
  */
 public static List getObjList(String db_name, String sql, Class clazz0,
   int limit) throws Exception {
  return getObjList(db_name, sql + " limit " + limit, clazz0);
 }


 
 
}

你可能感兴趣的:(DAO,sql,log4j,jdbc,idea)