druid 와 dbutils 를 통 해 데이터 베 이 스 를 패키지 합 니 다.

16646 단어 JAVAMySQL
package com.hq.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.hq.db.annotation.Column;
import com.hq.db.annotation.Exclude;
import com.hq.db.annotation.Table;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

/**
 * @author zth
 * @Date 2019-04-18 20:37
 *
 *            
 */


public class DB {

    private static Logger log = Logger.getLogger(DB.class);
    private static QueryRunner run = new QueryRunner();
    private static DruidDataSource ds = null;

    //         Connection
    private static ThreadLocal conn = new ThreadLocal<>();

    static {
        //       
        try{
            ResourceBundle res = ResourceBundle.getBundle("jdbc");
            ds = new DruidDataSource();
            ds.setUrl(res.getString("url"));
            ds.setDriverClassName(res.getString("driverClassName"));
            ds.setUsername(res.getString("username"));
            ds.setPassword(res.getString("password"));
            ds.setFilters(res.getString("filters"));
            ds.setMaxActive(Integer.parseInt(res.getString("maxActive")));
            ds.setInitialSize(Integer.parseInt(res.getString("initialSize")));
            ds.setMaxWait(Integer.parseInt(res.getString("maxWait")));
            ds.setMinIdle(Integer.parseInt(res.getString("minIdle")));
            //ds.setMaxIdle(Integer.parseInt(res.getString("maxIdle")));
            ds.setValidationQuery(res.getString("validationQuery"));
            ds.setTestWhileIdle(Boolean.parseBoolean(res.getString("testWhileIdle")));
            ds.setTestOnBorrow(Boolean.parseBoolean(res.getString("testOnBorrow")));
            ds.setTestOnReturn(Boolean.parseBoolean(res.getString("testOnReturn")));
            ds.setTimeBetweenEvictionRunsMillis(Long.parseLong(res.getString("timeBetweenEvictionRunsMillis")));
            ds.setMinEvictableIdleTimeMillis(Long.parseLong(res.getString("minEvictableIdleTimeMillis")));
            //ds.setValidationQuery(res.getString("validationQuery"));

        } catch (SQLException e) {
            log.error("ERROR_001_com.hq.db.Db_        _line62"+e.getMessage());
        }
    }

    /**
     *     DruidDataSource    Connection
     * @return Connection   
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        //    ThreadLocal    Connection
        Connection con = conn.get();
        //       , con   ,      con
        if (null == con || con.isClosed()){
            con = ds.getConnection();
            conn.set(con);
        }
        return con;
    }

    // ---------------------------        -------------------------------------

    /**
     *     
     * @throws SQLException
     */
    public static void beginTransaction() throws SQLException{
        //  ThreadLocal  connection
        Connection con = conn.get();
        //         
        con.setAutoCommit(false);
        //          ThreadLocal 
        conn.set(con);
    }

    /**
     *     
     * @throws SQLException
     */
    public static void commitTransaction() throws SQLException {
        //  ThreadLocal  connection
        Connection con = conn.get();
        //  con    ,    ,         
        if (con == null){
            throw new SQLException("      ,      ");
        }
        //    con    ,    
        con.commit();
        //      ,    
        con.close();
        // ThreadLocal     
        conn.remove();
    }

    /**
     *      
     */
    public static void rollbackTransaction(){
        try {
            //   ThreadLocal    connection
            Connection con = conn.get();
            //   con    ,    ,         ,      
            if (con == null){
                throw new SQLException("      ,      ");
            }
            //     
            con.rollback();
            //     
            con.close();
            //       ThreadLocal
            conn.remove();
        }catch (SQLException e){
            log.error("ERROR_002_com.hq.db_      _line134..."+e.getMessage());
        }
    }

    /**
     *     
     * @param connection
     * @throws SQLException
     */
    public static void releaseConnection(Connection connection) throws SQLException {
        //  ThreadLocal  connection
        Connection con = conn.get();
        //                ,             ,    ,        
        if (connection != null && con != connection){
            //         ,   
            if (!connection.isClosed()){
                connection.close();
            }
        }
    }

    /**
     *    DruidDataSource
     */
    public static void closeDataSource(){
        if (null!=ds){
            ds.close();
        }
    }

    // -----------------------   QueryRunner     --------------------------
    public static int[] batch(String sql,Object[][] params) throws SQLException {
        Connection con = getConnection();
        int[] result = run.batch(sql,params);
        releaseConnection(con);
        return result;
    }

    public static  T query(String sql ,ResultSetHandler handler,Object... params) throws SQLException {
        Connection con = getConnection();
        T result = run.query(con,sql,handler,params);
        releaseConnection(con);
        return result;
    }

    public static  T query(String sql, ResultSetHandler handler) throws SQLException {
        Connection con = getConnection();
        T result = run.query(con,sql,handler);
        releaseConnection(con);
        return result;

    }

    public static int update(String sql,Object... params) throws SQLException{
        Connection con = getConnection();
        int result = run.update(con,sql,params);
        releaseConnection(con);
        return result;
    }

    public static int update(String sql,Object params) throws SQLException{
        Connection con = getConnection();
        int result = run.update(con,sql,params);
        releaseConnection(con);
        return result;
    }

    public static int update(String sql) throws SQLException{
        Connection con = getConnection();
        int result = run.update(con,sql);
        releaseConnection(con);
        return result;
    }

    //------------------------      -----------------------------------------------

    /**
     *     
     * @param clazz
     * @param 
     * @return
     */
    public static  String getTableName(Class clazz){
        String result = null;
        Annotation ano = clazz.getDeclaredAnnotation(Table.class);
        if (null != ano && ano instanceof Table){
            Table table = (Table)ano;
            result = table.value();
        }else {
            //        ,       
            String allName = clazz.getName();
            int lastDot = allName.lastIndexOf(".");
            result = allName.substring(lastDot+1).toLowerCase();
        }
        return result;
    }

    /**
     *      ,         map
     * @param t
     * @param 
     * @return
     */
    public static TreeMap parseAllField(T t){
        TreeMap map = new TreeMap<>();

        Field[] fields = t.getClass().getDeclaredFields();
        if (fields != null && fields.length >0){
            for (Field field:fields) {
                String fname = field.getName();
                //     
                if ("id".equals(fname)) continue;
                if ("serialVersionUID".equals(fname)) continue;

                Annotation ano = field.getAnnotation(Exclude.class);
                if (null != ano && ano instanceof Exclude) continue;

                //     
                Annotation clm = field.getAnnotation(Column.class);
                field.setAccessible(true);

                try {
                    //                 
                    if (null == field.get(t)) continue;

                    if (null != clm && clm instanceof Column){
                        map.put(((Column)clm).value(),field.get(t));
                    }else {
                        map.put(fname,field.get(t));
                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return map;
    }

    /**
     *  Map          ( =?)  
     * @param flist (eg.name=?,age=?)
     * @param values     
     * @param map      TreeMap
     */
    public static void parseFildAndQuery(StringBuilder flist, List values,TreeMap map){
        if (null!=map && null!= map.keySet() && map.keySet().size()>0){
            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()){
                String key = iterator.next();
                flist.append(key+"=?,");
                values.add(map.get(key));
            }
        }

        if (flist.length()>0){
            flist.delete(flist.length()-1,flist.length());
        }
    }

    /**
     *    map          flist,qlist ,values 
     * @param flist    +"," (eg."name,age,sex")
     * @param qlist ?+","   (eg."?,?,?")
     * @param values       
     * @param map
     */
    public static void parseFildAndQuery(StringBuilder flist, StringBuilder qlist,List values,TreeMap map){
        if (null!=map && null!= map.keySet() && map.keySet().size()>0){
            Iterator iterator = map.keySet().iterator();
            while (iterator.hasNext()){
                String key = iterator.next();
                flist.append(key+",");
                qlist.append("?,");
                values.add(map.get(key));
            }
        }
        if (flist.length()>0){
            flist.delete(flist.length()-1,flist.length());
            qlist.delete(qlist.length()-1,qlist.length());
        }
    }


    //-----------------------          -------------------------------------------

    /**
     *           
     * @param t       
     * @return        id,   -1      
     * @throws SQLException
     */
    public static  long add(T t) throws SQLException {
        //     
        String tname = getTableName(t.getClass());

        TreeMap map = parseAllField(t);

        StringBuilder flist = new StringBuilder();
        StringBuilder qlist = new StringBuilder();
        List values = new ArrayList<>();

        parseFildAndQuery(flist,qlist,values,map);

        String sql = "insert into "+tname+"("+flist.toString()+") values ("+qlist.toString()+")";
        //   sql   t    

        update(sql,values.toArray());

        Object lastId = query("select LAST_INSERT_ID() from dual",new ArrayHandler())[0];
        long reLastId = -1;
        if (null != lastId && lastId instanceof Long){
            reLastId = ((Long)lastId).longValue();
        }else if (null != lastId && lastId instanceof BigInteger){
            reLastId = ((BigInteger)lastId).longValue();
        }
        return reLastId;
    }

    /**
     *     
     * @param t
     * @param 
     * @throws SQLException
     */
    public static void update(T t) throws SQLException{
        String tname = getTableName(t.getClass());
        TreeMap map = parseAllField(t);
        StringBuilder flist = new StringBuilder();
        List values = new ArrayList<>();

        //  Map          ( =?)  
        parseFildAndQuery(flist,values,map);

        String sql = "update "+tname+" set "+flist.toString()+" where id =?";
        log.debug(sql);

        //    id
        try {
            Field field = t.getClass().getDeclaredField("id");
            field.setAccessible(true);
            values.add(field.get(t));
            update(sql,values.toArray());
        } catch (NoSuchFieldException|IllegalAccessException e) {
            log.error("ERROR_003_com.hq.db.Db_line376_         ");
        }
    }

    /**
     *     
     * @throws SQLException
     */
    public static void delete(long id,Class clazz) throws SQLException{
        String tname = getTableName(clazz);
        String sql = "delete from "+tname+" where id =?";
        update(sql,id);
    }

    /**
     *       
     * @param id
     * @param clazz
     * @param 
     * @return
     * @throws SQLException
     */
    public static  T get(long id,Class clazz)throws SQLException{
        T t = null;
        String tname = getTableName(clazz);
        String sql = "select * from "+tname+" where id = ?";

        t = query(sql,new BeanHandler(clazz),id);
        return t;
    }

    /**
     *         
     */
    public static  List getAll(Class clazz) throws SQLException{
        List list = new ArrayList<>();
        String tname = getTableName(clazz);
        String sql = "select * from "+tname+" order by id desc";
        list = query(sql,new BeanListHandler(clazz));
        return list;
    }

    public static  List getAll(Class clazz,String sql) throws SQLException{
        List list = new ArrayList<>();
        String tname = getTableName(clazz);
        list = query(sql,new BeanListHandler(clazz));
        return list;
    }

    public static  List getAll(Class clazz,String sql,Object... params) throws SQLException{
        List list = new ArrayList<>();
        String tname = getTableName(clazz);
        list = query(sql,new BeanListHandler(clazz),params);
        return list;
    }

    //-------------------------------      ----------------------------------------

    /**
     *        
     * @param clazz
     * @param pageNO
     * @param pageSize
     * @param 
     * @return
     * @throws SQLException
     */
    public static  PageDiv getByPage(Class clazz,int pageNO,int pageSize) throws SQLException{
        PageDiv pageDiv = null;
        //       
        List list = new ArrayList<>();

        String tname = getTableName(clazz);
        String sql = "select * from "+tname+" order by id desc limit ?,?";
        log.debug(sql);
        list = query(sql,new BeanListHandler(clazz),(pageNO-1)*pageSize,pageSize);

        String sqltotal = "select count(id) from "+tname;

        Object re = query(sqltotal,new ArrayHandler())[0];

        long total = 0;
        if (null != re && re instanceof Long){
            total = (Long) re;
        }

        pageDiv = new PageDiv(pageNO,pageSize,total,list);
        return pageDiv;
    }

    public static  PageDiv getByPage(Class clazz,String sql,int pageNo,int pageSize,Object... param) throws SQLException{
        PageDiv pageDiv = null;
        //      
        List list = new ArrayList<>();

        Object[] params = new Object[param.length+2];
        System.arraycopy(param,0,params,0,param.length);
        params[param.length] = (pageNo-1)*pageSize;
        params[param.length+1] = pageSize;

        list = query(sql+"limit ?,?",new BeanListHandler(clazz),params);
        // select a,b,c from d where e...
        int fromStart = sql.toLowerCase().indexOf("from");
        String totalsql = "select count(id) "+sql.substring(fromStart);

        Object re = query(totalsql,new ArrayHandler(),param)[0];

        long total = 0;
        if (null != re && re instanceof Long){
            total = (Long) re;
        }

        pageDiv = new PageDiv(pageNo,pageSize,total,list);
        return pageDiv;

    }

}

전송 문:
druid 설정
log4j 설정

좋은 웹페이지 즐겨찾기