我项目使用的数据库连接管理、事务管理类(欢迎拍砖)

来源:互联网 发布:域名和空间的关系 编辑:程序博客网 时间:2024/04/30 21:23

       我在项目中使用的数据库连接、以及事务操作的类,类中采用开源的apache Dbutils作为辅助,Bonecp做为数据源,使用时请加上Dbutils包,Bonncp包,还有Log4j包。

DbUtils下载地址为Dbutils下载


Bonecp下载地址为BonecP下载


Bonecp需要google的集合框架,下载地址为guava下载,还需要SLF4J日志库,下载地址为slf4j下载

import com.jolbox.bonecp.BoneCPConfig;import com.jolbox.bonecp.BoneCPDataSource;import org.apache.commons.dbutils.DbUtils;import org.apache.log4j.Logger;import tqw.core.exc.DaoException;import tqw.util.Prop;import javax.sql.DataSource;import java.sql.Connection;import java.sql.SQLException;import java.util.Properties;/** * <p>数据库连接帮助类,包括事务处理</p> * Created by 淘情网. * User: 吴红军. * Date: 11-12-15 * Time: 上午2:20 */public final class DBUtil {    private static final Logger log = Logger.getLogger(DBUtil.class);    private static DataSource ds=null;    private static final ThreadLocal<Connection> local=new ThreadLocal<Connection>();    static {        init();    }    public static void init(){        Properties prop = Prop.getProperties("jdbc.properties");        BoneCPConfig cfg= null;        try{            Class.forName("com.mysql.jdbc.Driver");            cfg = new BoneCPConfig(prop);            ds = new BoneCPDataSource(cfg);        }catch (Exception ex){            log.error("数据源加载出现错误!",ex);            throw new DaoException("数据库源加载出现错误:"+ex.getMessage());        }finally {            if(cfg!=null){cfg=null;}            if(prop!=null)prop.clear();            prop=null;        }    }    /**     * 关闭连接方法     */    public static  void closeConn(){        Connection conn = local.get();        try {            if(conn!=null&&!conn.isClosed()){                conn.setAutoCommit(true);                conn.close();            }        } catch (SQLException e) {            log.error("无法关闭连接!!! ", e);            throw new DaoException("关闭连接错误!!!",e);        }finally {            local.set(null);        }    }    /**     * 获取数据库连接     * @return 数据库连接     */    public static Connection getConn() {        Connection conn = local.get();        try{            if(null==conn||conn.isClosed()){                //conn=bcp.getConnection();                conn = ds.getConnection();                local.set(conn);            }        }catch (SQLException e) {            throw new DaoException("获取数据库连接出现错误!",e);        }        return conn;    }    /**     * 断开连接池     */    public static void closeDataSource(){        try {            //bcp.close();            ds.getClass().getMethod("close").invoke(ds);        } catch (Exception e) {            log.error("释放数据源发生错误!",e);            throw new DaoException("释放数据源发生错误:"+e.getMessage());        }    }    /**事务开始*/    public static void begin(){        try{            Connection conn=getConn();            if(null!=conn&&!conn.isClosed())                conn.setAutoCommit(false);        }catch (SQLException e){            log.error("开启事务失败!",e);            throw new DaoException("开启事务失败!",e);        }    }    /**     * 事务提交     */    public static void commit(){        Connection conn=getConn();        DbUtils.commitAndCloseQuietly(conn);    }    /**     * 事务回滚     */    public static void rollback(){        Connection conn=getConn();        DbUtils.rollbackAndCloseQuietly(conn);    }    public static void close(){DBUtil.closeConn();}    /**     * 销毁方法     */    public static void destroy(){        /**/        closeDataSource();        ds=null;        //bcp=null;        log.debug("释放数据源完毕......");    }}
上面源码中包含了一个异常类DaoException,是我在项目中为了统一异常,自定义的,如下:

/** * <p>数据库自定义异常</p> * Created by 淘情网. * User: 吴红军. * Date: 11-12-13 * Time: 下午8:32 */public class DaoException extends RuntimeException{    public DaoException(String s) {        super(s);    }    public DaoException(String s, Throwable e) {        super(s, e);    }    public DaoException(Throwable e) {        super(e);    }}

属性读取方法Prop.getProperties(),因为Prop类不便公开,我这里提供这个方法吧,关闭文件流我用的是Apache的IO包,自行下载。

/** * 根据配置文件读取一个属性文件 * @param is 配置文件路径文件流 * @return Properties */public static Properties getProperties(InputStream is){Properties props=new Properties();try {props.load(is);return props;} catch (IOException e) {throw new SysException("读取配置文件错误!");}finally{IOUtils.closeQuietly(is);}}    /**     * 根据路径读取配置文件     * @param name 路径名称     * @return     */    public static Properties getProperties(String name){        return getProperties(Thread.currentThread().getContextClassLoader().getResourceAsStream(name));    }



其中用到了一个Properties属性文件,用来配置数据库地址,用户名和密码的,其他的属性请参考Bonecp属性,请放入你的类路径下,也可以自己更改路径,其中的属性根据你的项目自行修改,内容如下:

jdbcUrl=jdbc:mysql://localhost:3306/tqw?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&zeroDateTimeBehavior=convertToNullusername=rootpassword=rootidleMaxAgeInMinutes=240maxConnectionsPerPartition=30minConnectionsPerPartition=10partitionCount=2closeConnectionWatch=falsecloseConnectionWatchTimeoutInMs=0logStatementsEnabled=true#\u5f53\u8fde\u63a5\u6c60\u4e2d\u7684\u8fde\u63a5\u8017\u5c3d\u7684\u65f6\u5019 BoneCP\u4e00\u6b21\u540c\u65f6\u83b7\u53d6\u7684\u8fde\u63a5\u6570acquireIncrement=5statementsCacheSize=50releaseHelperThreads=3



原创粉丝点击