QueryRunner及其加强,以及JdbcUtils增长事务处理及多线程并发安全

1、QueryRunner使用java

QueryRunner是dbutils包下一个为了加强JDBC的类,使用以前须要先导jar包,jar包下载地址为:http://commons.apache.org/proper/commons-dbutils/sql

简化了JDBC中数据操做,以及数据与对象之间的转化。有几个经常使用方法。数据库

涉及到事务时建立QueryRunner对象时,不须要传入参数,但须要在方法里传入和其余层同一个Connection对象。apache

不涉及到事务时,建立QueryRunner对象,须要提供一个DateSource对象,QueryRunner内部从链接池得到链接安全

update()方法:网络

1.int update(String sql,Object...params)-->可执行增、删、改语句并发

2.int update(Connection conn,String sql,Object...params)-->一样支持增、删、改操做,可是方法无论理Connection了,支持事务。框架

 

    @Test
 public  void insert(){
     try {
QueryRunner qr
=new QueryRunner(C3p0Utils.getDateSource()); String sql="update bank set blance=blance+? where name=?"; Object[] o={200,"李四"}; qr.update(sql, o); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }

 

query()方法:ide

1.T query(String sql,ResultSetHandler rsh,Object...params)-->可执行查询工具

2.T query(Connection conn,String sql,ResultSetHandler rsh,Object...params)-->可执行查询,支持事务

update方法和query方法参数里面有一处不一样,里面增长了一个ResultSetHandler接口,做用是为了把从数据库中查询出来的数据转化成对象,有五种实现

1.BeanHandler(单行) -->构造器须要一个Class类型参数,用来把一行结果转换成指定类型的javaBean对象,前提是JavaBean对象里面的参数名称和数据库里面的参数名称要相同

2.BeanListHandler(多行)-->构造器也须要一个Class类型的参数,用来把一行结果集转换成一个javaBean,那么多行就是转换成list.

3.MapHandler(单行)-->把一行结果集转换成Map对象

4.MapListHandler(多行)-->把一行记录转换成一个Map,多行就是多个Map,即List<Map>

5.ScalarHandler(单行单列)-->一般用与Select count(*) from table 语句,返回一个Object.

    @Test
 public  void query(){
     try {
        QueryRunner qr=new QueryRunner(C3p0Utils.getDateSource());
        String sql="select * from bank";
        Bank b=qr.query(sql, new BeanHandler(Bank.class));
        System.out.println(b);
        
        
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     
 }

 

 

 2、JdbcUtils自写工具类增长事务处理。 

 在项目框架搭建过程当中,涉及到三个层面,数据层、业务层、网络层,这是在MVC模式基础上进一步的业务分离。Dao层是对数据库进行操做的,这里不涉及到任何的业务处理,因此事务不应出如今这里,Service层是进行业务处理的,事务应该在这里出现,事务的开始和结束都得依靠Connection对象,因此须要Connection对象,可是Connection只应该出如今Dao层中,不该该在Service中出现,因此要进行封装,在这里为了线程安全,使用ThreadLocal对象,而且业务逻辑进行判断,使经过一个事务中只使用同一个Connection对象。

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * @author WangXinwei
 *从C3P0链接池获取链接
 *getDateSource返回链接池对象
 */
public class C3p0Utils {
 private static ComboPooledDataSource dataSource=new ComboPooledDataSource();
 //为了并发安全,使用ThreadLocal对象
 private static ThreadLocal<Connection>  tl=new ThreadLocal<Connection>();
 /**
  * 
  * @return
  * @throws SQLException
  * 返回链接,首先判断线程是否含有链接,若是没有,则新建链接
  */
 public static Connection getConnection() throws SQLException{
     Connection con=tl.get();
     if(con!=null) return con;
     return dataSource.getConnection();
 }
 /**
  * 开启事务
 * @throws SQLException 
  */
 public static void beginTransaction() throws SQLException{
     Connection con=tl.get();
     if(con!=null) throw new RuntimeException("已经开启了事务");
     con=getConnection();
     con.setAutoCommit(false);
     tl.set(con);
 }
 /**
 * @throws SQLException 
  *提交事务
  */
public static void commitTransaction() throws SQLException{
    Connection con=tl.get();
     if(con==null) throw new RuntimeException("没有事务");
     con.commit();
     con.close();
     tl.remove();
 }
/**
 * @throws SQLException 
 * 回滚事务
 */
public static void rollbackTransaction() throws SQLException{
    Connection con=tl.get();
     if(con==null) throw new RuntimeException("没有事务");
     con.rollback();
     con.close();
     tl.remove();
}
/**
 * 
 * @param connection
 * @throws SQLException
 * 判断是否可以关闭链接,若是不属于事务那么就关闭。
 */
 public static void releaseConnection(Connection connection) throws SQLException{
     Connection con=tl.get();
     if(con==null) connection.close();
     if(con!=connection) connection.close();
 }
 /**
  * 
  * @return
  * 返回链接池对象
  */
 public static DataSource getDateSource(){
   return dataSource;
 
 }
}

3、QueryRunner加强

    @Test
 public  void queryBank(){
     try {
        QueryRunner qr=new QueryRunner();
        String sql="select * from bank";
        Connection con=C3p0Utils.getConnection();
        Bank b=qr.query(con,sql, new BeanHandler(Bank.class));
        C3p0Utils.releaseConnection(con);
        
        
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     
 }

本身提供链接与判断是否能够关闭链接,致使代码臃肿,能够把这下方法哦QueryRunner中实现,写一个QueryRunner的继承类

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

public class BasicQueryRunner extends QueryRunner {

    @Override
    public int[] batch(String sql, Object[][] params) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        int[] result=super.batch(con,sql, params);
        C3p0Utils.releaseConnection(con);
        return result;
    }

    @Override
    public int execute(String sql, Object... params) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        int result=super.execute(con,sql, params);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public <T> List<T> execute(String sql, ResultSetHandler<T> rsh,
            Object... params) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        List<T> result=super.execute(con,sql, rsh, params);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public <T> T insert(String sql, ResultSetHandler<T> rsh, Object... params)
            throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        T result=super.insert(con,sql, rsh, params);
        C3p0Utils.releaseConnection(con);
        return result;

    }

    @Override
    public <T> T insert(String sql, ResultSetHandler<T> rsh)
            throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        T result=super.insert(con,sql, rsh);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public <T> T insertBatch(String sql, ResultSetHandler<T> rsh,
            Object[][] params) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        T result=super.insertBatch(con,sql, rsh, params);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public <T> T query(String sql, ResultSetHandler<T> rsh, Object... params)
            throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        T result=super.query(con,sql, rsh, params);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public <T> T query(String sql, ResultSetHandler<T> rsh) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        T result= super.query(con,sql, rsh);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public int update(String sql, Object... params) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        int result= super.update(con,sql, params);
        C3p0Utils.releaseConnection(con);
        return result;
    
    }

    @Override
    public int update(String sql, Object param) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        int result= super.update(con,sql, param);
        C3p0Utils.releaseConnection(con);
        return result;
        
    }

    @Override
    public int update(String sql) throws SQLException {
        // TODO Auto-generated method stub
        Connection con=C3p0Utils.getConnection();
        int result=super.update(con,sql);
        C3p0Utils.releaseConnection(con);
        return result;
     
    }

    


}
相关文章
相关标签/搜索