网上图书商城项目学习笔记-035工具类之JdbcUtils及TxQueryRunner及C3P0配置

事务就是保证多个操作在同一个connection,TxQueryRunner通过JdbcUtils获取连接,而JdbcUtils通过ThreadLocal<Connection>确保了不同线程设置的con不会混淆(tl.set(con)),而同一线程的connecion可以共用,从而具有事务的功能

1.JdbcUtils.java

 1 package cn.itcast.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 
 6 import javax.sql.DataSource;
 7 
 8 import com.mchange.v2.c3p0.ComboPooledDataSource;
 9 
10 /**
11  * 使用本类的方法,必须提供c3p0-copnfig.xml文件
12  * @author qdmmy6
13  */
14 public class JdbcUtils {
15     // 饿汉式
16     private static DataSource ds = new ComboPooledDataSource();
17     
18     /**
19      * 它为null表示没有事务
20      * 它不为null表示有事务
21      * 当开启事务时,需要给它赋值
22      * 当结束事务时,需要给它赋值为null
23      * 并且在开启事务时,让dao的多个方法共享这个Connection
24      */
25     private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
26     
27     public static DataSource getDataSource() {
28         return ds;
29     }
30     
31     /**
32      * dao使用本方法来获取连接
33      * @return
34      * @throws SQLException
35      */
36     public static Connection getConnection() throws SQLException {
37         /*
38          * 如果有事务,返回当前事务的con
39          * 如果没有事务,通过连接池返回新的con
40          */
41         Connection con = tl.get();//获取当前线程的事务连接
42         if(con != null) return con;
43         return ds.getConnection();
44     }
45     
46     /**
47      * 开启事务
48      * @throws SQLException 
49      */
50     public static void beginTransaction() throws SQLException {
51         Connection con = tl.get();//获取当前线程的事务连接
52         if(con != null) throw new SQLException("已经开启了事务,不能重复开启!");
53         con = ds.getConnection();//给con赋值,表示开启了事务
54         con.setAutoCommit(false);//设置为手动提交
55         tl.set(con);//把当前事务连接放到tl中
56     }
57     
58     /**
59      * 提交事务
60      * @throws SQLException 
61      */
62     public static void commitTransaction() throws SQLException {
63         Connection con = tl.get();//获取当前线程的事务连接
64         if(con == null) throw new SQLException("没有事务不能提交!");
65         con.commit();//提交事务
66         con.close();//关闭连接
67         con = null;//表示事务结束!
68         tl.remove();
69     }
70     
71     /**
72      * 回滚事务
73      * @throws SQLException 
74      */
75     public static void rollbackTransaction() throws SQLException {
76         Connection con = tl.get();//获取当前线程的事务连接
77         if(con == null) throw new SQLException("没有事务不能回滚!");
78         con.rollback();
79         con.close();
80         con = null;
81         tl.remove();
82     }
83     
84     /**
85      * 释放Connection
86      * @param con
87      * @throws SQLException 
88      */
89     public static void releaseConnection(Connection connection) throws SQLException {
90         Connection con = tl.get();//获取当前线程的事务连接
91         if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!
92             if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之!
93                 connection.close();
94             }
95         }
96     }
97 }

2.TxQueryRunner

 1 package cn.itcast.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.SQLException;
 5 
 6 import org.apache.commons.dbutils.QueryRunner;
 7 import org.apache.commons.dbutils.ResultSetHandler;
 8 
 9 public class TxQueryRunner extends QueryRunner {
10 
11     @Override
12     public int[] batch(String sql, Object[][] params) throws SQLException {
13         Connection con = JdbcUtils.getConnection();
14         int[] result = super.batch(con, sql, params);
15         JdbcUtils.releaseConnection(con);
16         return result;
17     }
18 
19     @Override
20     public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
21             throws SQLException {
22         Connection con = JdbcUtils.getConnection();
23         T result = super.query(con, sql, rsh, params);
24         JdbcUtils.releaseConnection(con);
25         return result;
26     }
27     
28     @Override
29     public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
30         Connection con = JdbcUtils.getConnection();
31         T result = super.query(con, sql, rsh);
32         JdbcUtils.releaseConnection(con);
33         return result;
34     }
35 
36     @Override
37     public int update(String sql) throws SQLException {
38         Connection con = JdbcUtils.getConnection();
39         int result = super.update(con, sql);
40         JdbcUtils.releaseConnection(con);
41         return result;
42     }
43 
44     @Override
45     public int update(String sql, Object param) throws SQLException {
46         Connection con = JdbcUtils.getConnection();
47         int result = super.update(con, sql, param);
48         JdbcUtils.releaseConnection(con);
49         return result;
50     }
51 
52     @Override
53     public int update(String sql, Object... params) throws SQLException {
54         Connection con = JdbcUtils.getConnection();
55         int result = super.update(con, sql, params);
56         JdbcUtils.releaseConnection(con);
57         return result;
58     }
59 }

3.c3p0-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config> 
        <property name="jdbcUrl">
            <![CDATA[
                jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=UTF8&useServerPrepStmts=true&prepStmtCacheSqlLimit=256&cachePrepStmts=true&prepStmtCacheSize=256&rewriteBatchedStatements=true
            ]]>
        </property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">1234</property>
        
        <property name="acquireIncrement">3</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">2</property>
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>

 

posted @ 2016-02-04 17:14  shamgod  阅读(379)  评论(0编辑  收藏  举报
haha