zoukankan      html  css  js  c++  java
  • Apache-dbutils 简介及事务处理

    一:commons-dbutils简介

      commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。

    DbUtils提供了三个包,分别是:
    org.apache.commons.dbutils;
    org.apache.commons.dbutils.handlers;
    org.apache.commons.dbutils.wrappers;

    (1)org.apache.commons.dbutils
    DbUtils 关闭链接等操作
    QueryRunner 进行查询的操作

    (2)org.apache.commons.dbutils.handlers
    ArrayHandler :将ResultSet中第一行的数据转化成对象数组
    ArrayListHandler将ResultSet中所有的数据转化成List,List中存放的是Object[]
    BeanHandler :将ResultSet中第一行的数据转化成类对象
    BeanListHandler :将ResultSet中所有的数据转化成List,List中存放的是类对象
    ColumnListHandler :将ResultSet中某一列的数据存成List,List中存放的是Object对象
    KeyedHandler :将ResultSet中存成映射,key为某一列对应为Map。Map中存放的是数据
    MapHandler :将ResultSet中第一行的数据存成Map映射
    MapListHandler :将ResultSet中所有的数据存成List。List中存放的是Map
    ScalarHandler :将ResultSet中一条记录的其中某一列的数据存成Object

    (3)org.apache.commons.dbutils.wrappers
    SqlNullCheckedResultSet :对ResultSet进行操作,改版里面的值
    StringTrimmedResultSet :去除ResultSet中中字段的左右空格。Trim()

    二:JDBC开发中的事务处理

    开发中,对数据库的多个表或者对一个表中的多条数据执行更新操作时要保证对多个更新操作要么同时成功,要么都不成功,这就涉及到对多个更新操作的事务管理问题了。

    (1)在数据访问层(Dao)中处理事务

          /**
          * @Method: transfer
          * @Description:
          * 在开发中,DAO层的职责应该只涉及到CRUD,
          * 所以在开发中DAO层出现这样的业务处理方法是完全错误的
          * @throws SQLException
         */
         public void transfer() throws SQLException{
             Connection conn = null;
             try{
                 conn = JdbcUtils.getConnection();
                 //开启事务
                 conn.setAutoCommit(false);

                /**
                  * 在创建QueryRunner对象时,不传递数据源给它,是为了保证这两条SQL在同一个事务中进行,
                  * 我们手动获取数据库连接,然后让这两条SQL使用同一个数据库连接执行
                  */
                QueryRunner runner = new QueryRunner();
                String sql1 = "update account set money=money-100 where name=?";
                String sql2 = "update account set money=money+100 where name=?";
                Object[] paramArr1 = {param1};
                Object[] paramArr2 = {param2};
                runner.update(conn,sql1,paramArr1);
                //模拟程序出现异常让事务回滚
                int x = 1/0;
                runner.update(conn,sql2,paramArr2);
                
                //sql正常执行之后就提交事务
                conn.commit();
                
              }catch (Exception e) {
                 e.printStackTrace();
                 if(conn!=null){
                     //出现异常之后就回滚事务
                     conn.rollback();
                 }
             }finally{
                 //关闭数据库连接
                 conn.close();       
            }
         }

    在开发中,DAO层的职责应该只涉及到基本的CRUD,不涉及具体的业务操作,所以在开发中DAO层出现这样的业务处理方法是一种不好的设计

    (2)在业务层(Service)处理事务

    先改造DAO:

    public class TextDao {
     
         //接收service层传递过来的Connection对象
         private Connection conn = null;
         
         public TextDao(Connection conn){
            this.conn = conn;
         }
         
         public TextDao(){

         }
         
         /**
         * @Method: update
         * @Description:更新
         * @Anthor:
         * @param user
         * @throws SQLException
         */
         public void update(Account account) throws SQLException{
             
             QueryRunner qr = new QueryRunner();
             String sql = "update account set name=?,money=? where id=?";
             Object params[] = {account.getName(),account.getMoney(),account.getId()};
             //使用service层传递过来的Connection对象操作数据库
             qr.update(conn,sql, params);
             
         }
         
         /**
         * @Method: find
         * @Description:查找
         * @Anthor:
         * @param id
         * @return
         * @throws SQLException
         */
         public Account findById(int id) throws SQLException{
             QueryRunner qr = new QueryRunner();
             String sql = "select * from account where id=?";
             //使用service层传递过来的Connection对象操作数据库
             return (Account) qr.query(conn,sql, id, new BeanHandler(Account.class));
         }
     }

    接着对Service(业务层)中的transfer方法的改造,在业务层(Service)中处理事务

    /**
     * @ClassName: TextService
     * @Description: 业务逻辑处理层
     * @author:
     * @date:
     *
     */
     public class TextService {
         
         /**
         * @Method: transfer
         * @Description:这个方法是用来处理两个用户之间的转账业务
         * @Anthor:
         * @param sourceid
         * @param tartgetid
         * @param money
         * @throws SQLException
         */
         public boolean transfer(int sourceid,int tartgetid,float money) throws SQLException{
             Connection conn = null;
             boolean flag = false;
             try{
                 //获取数据库连接
                 conn = JdbcUtils.getConnection();
                
                 //开启事务
                 conn.setAutoCommit(false);
                
                 //将获取到的Connection传递给TextDao,保证dao层使用的是同一个Connection对象操作数据库
                 TextDao dao = new TextDao(conn);
                 Account source = dao.find(sourceid);
                 Account target = dao.find(tartgetid);
                 
                 source.setMoney(source.getMoney()-money);
                 target.setMoney(target.getMoney()+money);
                 
                 dao.update(source);
                 //模拟程序出现异常让事务回滚
                 int x = 1/0;
                 dao.update(target);
                 //提交事务
                 conn.commit();
                 flag = true;
             }catch (Exception e) {
                 e.printStackTrace();
                 //出现异常之后就回滚事务
                 conn.rollback();
                  flag = false;
             }finally{
                 conn.close();
             }
             return flag;
         }
     }

    这样TextDao只负责CRUD,里面没有具体的业务处理方法了,职责就单一了,而TextService则负责具体的业务逻辑和事务的处理,需要操作数据库时,就调用TextDao层提供的CRUD方法操作数据库。

    (3)使用ThreadLocal进行更加优雅的事务处理

    注:ThreadLocal使用场合主要解决多线程中数据因并发产生不一致问题(解决线程安全)。ThreadLocal为每个线程中并发访问的数据提供一个独立副本,副本之间相互独立(独立操作),这样每一个线程都可以随意修改自己的变量副本,而不会对其他线程产生影响。通过访问副本来运行业务,这样的结果是耗费了内存,单大大减少了线程同步所带来性能消耗,也减少了线程并发控制的复杂度。

    (ThreadLocal和Synchonized都用于解决多线程并发访问,synchronized是利用锁的机制,使变量或代码块在某一时该只能被一个线程访问。而ThreadLocal为每一个线程都提供了变量的副本,使得每个线程在某一时间访问到的并不是同一个对象,这样就隔离了多个线程对数据的数据共享)

    Synchronized用于线程间的数据共享,而ThreadLocal则用于线程间的数据隔离。

    ThreadLocal类的使用范例如下:

      public class ThreadLocalTest {
     
         public static void main(String[] args) {
             //得到程序运行时的当前线程
             Thread currentThread = Thread.currentThread();
            
             System.out.println(currentThread);
             //ThreadLocal一个容器,向这个容器存储的对象,在当前线程范围内都可以取得出来
             ThreadLocal<String> t = new ThreadLocal<String>();
             //把某个对象绑定到当前线程上 对象以键值对的形式存储到一个Map集合中,对象的的key是当前的线程,如: map(currentThread,"aaa")
             t.set("aaa");
             //获取绑定到当前线程中的对象
             String value = t.get();
             //输出value的值是aaa
             System.out.println(value);
         }
     }

    1:使用ThreadLocal类进行改造数据库连接工具类JdbcUtils,改造后的代码如下:

    /**
      * @ClassName: JdbcUtils2
      * @Description: 数据库连接工具类
      * @author:
      * @date:
      *
      */
      public class JdbcUtils2 {
          
          private static ComboPooledDataSource ds = null;
          
          //使用ThreadLocal存储当前线程中的Connection对象
          private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
          
          //在静态代码块中创建数据库连接池
          static{
              try{
                  //通过代码创建C3P0数据库连接池
                  /*ds = new ComboPooledDataSource();
                  ds.setDriverClass("com.mysql.jdbc.Driver");
                  ds.setJdbcUrl("jdbc:mysql://localhost:3306/jdbcstudy");
                  ds.setUser("root");
                  ds.setPassword("XDP");
                  ds.setInitialPoolSize(10);
                  ds.setMinPoolSize(5);
                  ds.setMaxPoolSize(20);*/
                  
                  //通过读取C3P0的xml配置文件创建数据源,C3P0的xml配置文件c3p0-config.xml必须放在src目录下
                  //ds = new ComboPooledDataSource();//使用C3P0的默认配置来创建数据源
                  ds = new ComboPooledDataSource("MySQL");//使用C3P0的命名配置来创建数据源
                  
              }catch (Exception e) {
                  throw new ExceptionInInitializerError(e);
              }
          }
          
          /**
          * @Method: getConnection
          * @Description: 从数据源中获取数据库连接
          * @Anthor:
          * @return Connection
          * @throws SQLException
          */
          public static Connection getConnection() throws SQLException{
          
              //从当前线程中获取Connection
              Connection conn = threadLocal.get();
              
              if(conn==null){
                  //从数据源中获取数据库连接
                  conn = getDataSource().getConnection();
                  //将conn绑定到当前线程
                  threadLocal.set(conn);
              }
              return conn;
          }
          
          /**
          * @Method: startTransaction
          * @Description: 开启事务
          * @Anthor:
          *
          */
          public static void startTransaction(){
              try{
                  Connection conn =  threadLocal.get();
                  if(conn==null){
                      conn = getConnection();
                       //把 conn绑定到当前线程上
                      threadLocal.set(conn);
                  }
                  
                  //开启事务
                  conn.setAutoCommit(false);
                  
              }catch (Exception e) {
                  throw new RuntimeException(e);
              }
          }
          
          /**
          * @Method: rollback
          * @Description:回滚事务
          * @Anthor:
          */
          public static void rollback(){
              try{
                  //从当前线程中获取Connection
                  Connection conn = threadLocal.get();
                  if(conn!=null){
                      //回滚事务
                      conn.rollback();
                  }
              }catch (Exception e) {
                 throw new RuntimeException(e);
              }
         }
         
         /**
         * @Method: commit
         * @Description:提交事务
         * @Anthor:
         */
         public static void commit(){
             try{
                 //从当前线程中获取Connection
                 Connection conn = threadLocal.get();
                 if(conn!=null){
                
                     //提交事务
                     conn.commit();
                    
                 }
             }catch (Exception e) {
                 throw new RuntimeException(e);
             }
         }
         
         /**
         * @Method: close
         * @Description:关闭数据库连接(注意,并不是真的关闭,而是把连接还给数据库连接池)
         * @Anthor:
         *
         */
         public static void close(){
             try{
                 //从当前线程中获取Connection
                 Connection conn = threadLocal.get();
                 if(conn!=null){
                     conn.close();
                      //解除当前线程上绑定conn
                     threadLocal.remove();
                 }
             }catch (Exception e) {
                 throw new RuntimeException(e);
             }
         }
         
         /**
         * @Method: getDataSource
         * @Description: 获取数据源
         * @Anthor:
         * @return DataSource
         */
         public static DataSource getDataSource(){
             //从数据源中获取数据库连接
             return ds;
         }
     }

    2:对TextDao进行改造,数据库连接对象不再需要service层传递过来,而是直接从JdbcUtils2提供的getConnection方法去获取,改造后的TextDao如下:

    /**
     * @ClassName: TextDao
     * @Description: 针对Account对象的CRUD
     * @author:
     * @date:
     *
     */
     public class TextDao2 {
     
         public void update(Account account) throws SQLException{
             
             QueryRunner qr = new QueryRunner();
             String sql = "update account set name=?,money=? where id=?";
             Object params[] = {account.getName(),account.getMoney(),account.getId()};
             //JdbcUtils2.getConnection()获取当前线程中的Connection对象
             qr.update(JdbcUtils2.getConnection(),sql, params);
             
         }
         
         public Account find(int id) throws SQLException{
             QueryRunner qr = new QueryRunner();
             String sql = "select * from account where id=?";
             //JdbcUtils2.getConnection()获取当前线程中的Connection对象
             return (Account) qr.query(JdbcUtils2.getConnection(),sql, id, new BeanHandler(Account.class));
         }
     }

    3:对TextService进行改造,service层不再需要传递数据库连接Connection给Dao层,改造后的TextService如下:

     public class TextService2 {
          
         /**
         * @Method: transfer
         * @Description:在业务层处理两个账户之间的转账问题
         * @Anthor:    
         * @param sourceid
         * @param tartgetid
         * @param money
         * @throws SQLException
         */
         public boolean transfer(int sourceid,int tartgetid,float money) throws SQLException{
              boolean flag = false;
             try{
                 //开启事务,在业务层处理事务,保证dao层的多个操作在同一个事务中进行
                 JdbcUtils2.startTransaction();
                
                 TextDao2 dao = new TextDao2 ();
                 
                 Account source = dao.find(sourceid);
                 Account target = dao.find(tartgetid);
                 source.setMoney(source.getMoney()-money);
                 target.setMoney(target.getMoney()+money);
                 
                 dao.update(source);
                 //模拟程序出现异常让事务回滚
                 int x = 1/0;
                 dao.update(target);
                 
                 //SQL正常执行之后提交事务
                 JdbcUtils2.commit();
                 flag = true;

            }catch (Exception e) {
                e.printStackTrace();
                 //出现异常之后就回滚事务
                 JdbcUtils2.rollback();
                 flag = false;
             }finally{
                 //关闭数据库连接
                 JdbcUtils2.close();
             }
             return flag;
         }
     }

    ThreadLocal类在开发中使用得是比较多的,程序运行中产生的数据要想在一个线程范围内共享,只需要把数据使用ThreadLocal进行存储即可。

    (4)ThreadLocal + Filter 处理事务

    ThreadLocal + Filter进行统一的事务处理,这种方式主要是使用过滤器进行统一的事务处理

    1、编写一个事务过滤器TransactionFilter

    /**
     * @ClassName: TransactionFilter
     * @Description:ThreadLocal + Filter 统一处理数据库事务
     * @author:
     * @date:
     *
     */
     public class TransactionFilter implements Filter {
     
         @Override
         public void init(FilterConfig filterConfig) throws ServletException {
     
         }
     
         @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                 FilterChain chain) throws IOException, ServletException {

             Connection connection = null;
             try {
                 //1、获取数据库连接对象Connection
                 connection = JdbcUtils.getConnection();
                
                 //2、开启事务
                 connection.setAutoCommit(false);
                
                 //3、利用ThreadLocal把获取数据库连接对象Connection和当前线程绑定
                 ConnectionContext.getInstance().bind(connection);
                
                 //4、把请求转发给目标Servlet
                 chain.doFilter(request, response);
                
                 //5、提交事务
                 connection.commit();
                
             } catch (Exception e) {
                 e.printStackTrace();
                 //6、回滚事务
                try {
                     connection.rollback();
                 } catch (SQLException e1) {
                     e1.printStackTrace();
                 }
                 HttpServletRequest req = (HttpServletRequest) request;
                 HttpServletResponse res = (HttpServletResponse) response;
                //req.setAttribute("errMsg", e.getMessage());
                //req.getRequestDispatcher("/error.jsp").forward(req, res);
                //出现异常之后跳转到错误页面
                 res.sendRedirect(req.getContextPath()+"/error.jsp");
             }finally{
                 //7、解除绑定
                 ConnectionContext.getInstance().remove();
                 //8、关闭数据库连接
                 try {
                     connection.close();
                 } catch (SQLException e) {
                     e.printStackTrace();
                 }
             }
         }
     
         @Override
         public void destroy() {
     
         }
     }

    2:我们在TransactionFilter中把获取到的数据库连接使用ThreadLocal绑定到当前线程之后,在DAO层还需要从ThreadLocal中取出数据库连接来操作数据库,因此需要编写一个ConnectionContext类来存储ThreadLocal,ConnectionContext类的代码如下:

    /**
      * @ClassName: ConnectionContext
      * @Description:数据库连接上下文
      * @author:
      * @date:
     */
     public class ConnectionContext {
     
        /**
         * 构造方法私有化,将ConnectionContext设计成单例
         */
         private ConnectionContext(){
             
         }
        
         //创建ConnectionContext实例对象
         private static ConnectionContext connectionContext = new ConnectionContext();
         
         /**
         * @Method: getInstance
         * @Description:获取ConnectionContext实例对象
         * @Anthor:
         * @return
         */
         public static ConnectionContext getInstance(){
             return connectionContext;
         }
         
         /**
         * @Field: connectionThreadLocal
         *         使用ThreadLocal存储数据库连接对象
         */
         private ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<Connection>();
         
         /**
         * @Method: bind
         * @Description:利用ThreadLocal把获取数据库连接对象Connection和当前线程绑定
         * @Anthor:
         * @param connection
         */
         public void bind(Connection connection){
             connectionThreadLocal.set(connection);
         }
         
         /**
         * @Method: getConnection
         * @Description:从当前线程中取出Connection对象
         * @Anthor:
         * @return
         */
         public Connection getConnection(){
             return connectionThreadLocal.get();
         }
         
         /**
         * @Method: remove
         * @Description: 解除当前线程上绑定Connection
         * @Anthor:
         *
         */
         public void remove(){
             connectionThreadLocal.remove();
         }
     }

    3:在DAO层想获取数据库连接时,就可以使用ConnectionContext.getInstance().getConnection()来获取,如下所示:

    /**
     * @ClassName: AccountDao
     * @Description: 针对Account对象的CRUD
     * @author:
     * @date:
     *
     */
     public class TextDao3 {
     
         public void update(Account account) throws SQLException{
             
             QueryRunner qr = new QueryRunner();
             String sql = "update account set name=?,money=? where id=?";
             Object params[] = {account.getName(),account.getMoney(),account.getId()};
             //ConnectionContext.getInstance().getConnection()获取当前线程中的Connection对象
             qr.update(ConnectionContext.getInstance().getConnection(),sql, params);
             
         }
         
         public Account find(int id) throws SQLException{
             QueryRunner qr = new QueryRunner();
             String sql = "select * from account where id=?";
             //ConnectionContext.getInstance().getConnection()获取当前线程中的Connection对象
             return (Account) qr.query(ConnectionContext.getInstance().getConnection(),sql, id, new BeanHandler(Account.class));
         }
     }

    4:Service层也不用处理事务和数据库连接问题了,这些统一在TransactionFilter中统一管理了,Service层只需要专注业务逻辑的处理即可,如下所示:

    public class TextService3 {
          
          /**
         * @Method: transfer
         * @Description:在业务层处理两个账户之间的转账问题
         * @Anthor:
         * @param sourceid
         * @param tartgetid
         * @param money
         * @throws SQLException
         */
         public void transfer(int sourceid, int tartgetid, float money)
                throws SQLException {
             TextDao3 dao = new TextDao3 ();
             Account source = dao.find(sourceid);
             Account target = dao.find(tartgetid);
             source.setMoney(source.getMoney() - money);
             target.setMoney(target.getMoney() + money);
             dao.update(source);
             // 模拟程序出现异常让事务回滚
             int x = 1 / 0;
             dao.update(target);
         }
     }

    5:Web层的Servlet调用Service层的业务方法处理用户请求,需要注意的是:调用Service层的方法出异常之后,继续将异常抛出,这样在TransactionFilter就能捕获到抛出的异常,继而执行事务回滚操作,如下所示:

    public class AccountServlet extends HttpServlet {

         public void doGet(HttpServletRequest request, HttpServletResponse response)
                 throws ServletException, IOException {
             TextService3 service = new TextService3();
             try {
                 service.transfer(1, 2, 100);
             } catch (SQLException e) {
                 e.printStackTrace();
                 //注意:调用service层的方法出异常之后,继续将异常抛出,这样在TransactionFilter就能捕获到抛出的异常,继而执行事务回滚操作
                 throw new RuntimeException(e);
             }
         }
     
         public void doPost(HttpServletRequest request, HttpServletResponse response)
                 throws ServletException, IOException {
             doGet(request, response);
         }
     }

  • 相关阅读:
    SQL Server 阻止了对组件 'Ole Automation Procedures' 的 过程'sys.sp_OACreate' 的访问
    谷歌浏览器扩展程序manifest.json参数详解
    获取天气api
    UVA 10385 Duathlon
    UVA 10668 Expanding Rods
    UVALIVE 3891 The Teacher's Side of Math
    UVA 11149 Power of Matrix
    UVA 10655 Contemplation! Algebra
    UVA 11210 Chinese Mahjong
    UVA 11384 Help is needed for Dexter
  • 原文地址:https://www.cnblogs.com/wpcnblog/p/11597397.html
Copyright © 2011-2022 走看看