美文网首页
Commons DbUtils 与 c3p0 结合使用

Commons DbUtils 与 c3p0 结合使用

作者: e辉 | 来源:发表于2018-03-01 11:58 被阅读98次

当编写一些小功能的的程序的时候,需要对数据库进行操作,如果我们还使用spring + mybatis 的方式来访问数据库的话,会显得略微庞大,这时可以使用Commons DbUtils 与 c3p0 结合,轻量小巧,很适合小项目开发。

简介

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

c3p0数据库连接池配置文件

在项目的src或resource目录下加入c3p0-config.xml 配置文件,配置如下

<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
    <default-config> 33 
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">dre@mtech1012</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>

数据库链接工具

获取c3p0链接池工具,并使用ThreadLocal来实现事务。

public class JdbcUtils {

    // 饿汉式
    private static DataSource ds = new ComboPooledDataSource();

    /**
     * 它为null表示没有事务
     * 它不为null表示有事务
     * 当开启事务时,需要给它赋值
     * 当结束事务时,需要给它赋值为null
     * 并且在开启事务时,让dao的多个方法共享这个Connection
     */
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    public static DataSource getDataSource() {
        return ds;
    }
    
    // 如果不把c3p0配置文件放在src或resource下的话,就使用如下方式加载
//    static {
//        try {
//            Properties prop = new Properties();
//            InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
//            prop.load(in);
//            BasicDataSourceFactory factory = new BasicDataSourceFactory();
//            ds = factory.createDataSource(prop);
//        } catch (Exception e) {
//            throw new ExceptionInInitializerError(e);
//        }
//    }

    /**
     * dao使用本方法来获取连接
     */
    public static Connection getConnection() throws SQLException {
        /*
         * 如果有事务,返回当前事务的con
         * 如果没有事务,通过连接池返回新的con
         */
        Connection con = tl.get();//获取当前线程的事务连接
        if (con != null) return con;
        return ds.getConnection();
    }

    /**
     * 开启事务
     */
    public static void beginTransaction() throws SQLException {
        Connection con = tl.get();//获取当前线程的事务连接
        if (con != null) throw new SQLException("已经开启了事务,不能重复开启!");
        con = ds.getConnection();//给con赋值,表示开启了事务
        con.setAutoCommit(false);//设置为手动提交
        tl.set(con);//把当前事务连接放到tl中
    }

    /**
     * 提交事务
     */
    public static void commitTransaction() throws SQLException {
        Connection con = tl.get();//获取当前线程的事务连接
        if (con == null) throw new SQLException("没有事务不能提交!");
        con.commit();//提交事务
        con.close();//关闭连接
        con = null;//表示事务结束!
        tl.remove();
    }

    /**
     * 回滚事务
     */
    public static void rollbackTransaction() throws SQLException {
        Connection con = tl.get();//获取当前线程的事务连接
        if (con == null) throw new SQLException("没有事务不能回滚!");
        con.rollback();
        con.close();
        con = null;
        tl.remove();
    }

    /**
     * 释放Connection
     */
    public static void releaseConnection(Connection connection) throws SQLException {
        Connection con = tl.get();//获取当前线程的事务连接
        if (connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!
            if (connection != null && !connection.isClosed()) {//如果参数连接没有关闭,关闭之!
                connection.close();
            }
        }
    }
}

dbutils 中的 CRUD

public class Demo {    
    
    @Test
    public void insert() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)";
        Object[] params = {2, "bbb", "123", "bbb@163.com", new Date()};
        runner.update(sql, params);
    }

    @Test
    public void update() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "update users set email=? where id=?";
        Object[] params = {"yeyiyi@126.com", 1};
        runner.update(sql, params);
    }

    @Test
    public void delete() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "delete from users where id=?";
        runner.update(sql, 2);
    }

    @Test
    public void find() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select * from users where id=?";
        User user = (User) runner.query(sql, 1, new BeanHandler(User.class));
        System.out.println(user.getEmail());
    }

    @Test
    public void getAll() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "select * from users";
        List list = (List) runner.query(sql, new BeanListHandler(User.class));
        System.out.println(list);
    }

    @Test
    public void batch() throws SQLException {
        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
        String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)";
        Object[][] params = new Object[3][5];
        for (int i = 0; i < params.length; i++) {
            params[i] = new Object[]{i+1, "aa"+i, "123", i+"@sian.com", new Date()};
        }
        runner.batch(sql, params);
    }
}

查询结果的封装

  • ArrayHandler:把结果集中的第一行数据转成对象数组。
  • ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。
  • BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
  • BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
  • ColumnListHandler:将结果集中某一列的数据存放到List中。
  • KeyedHandler(name):将结果集中的每一行数据都封装到一个Map里,再把这些map再存到一个map里,其key为指定的key。
  • MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
  • MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List。

相关文章

  • Commons DbUtils 与 c3p0 结合使用

    当编写一些小功能的的程序的时候,需要对数据库进行操作,如果我们还使用spring + mybatis 的方式来访问...

  • java 连接 mysql

    防止注入攻击,使用第二种方法 引用org.apache.commons.dbutils.DbUtils 封装的这个...

  • DBUtils工具类

    API简介Commons-dbutils的核心是两个类org.apache.commons.dbutils.DBU...

  • commons-dbutils工具介绍及实战

    1.commons-dbutils简介 commons-dbutils 是 Apache 组织提供的一个开源 JD...

  • Apache Commons DbUtils工具包使用介绍

    这篇文章主要介绍了Apache Commons DbUtils工具包使用介绍,本文介绍了DBUtils是什么东西、...

  • commons-dbutils 使用

    commons-dbutils 是什么 commons-dbutils 有什么用 简化jdbc编码 优化数据库结果...

  • DbUtils

    分类说明名称DbUtils全称Commons DbUtils功能数据库操作组件 Common DbUtils是由A...

  • DBUtils

    一、DBUtils简介 1、DBUtils是Apache Commons组件中的一员,开源免费2、DBUtils是...

  • dbutils工具

    commons=dbutils是对JDBC的简单封装API介绍:• org.apache.commons.db...

  • 接口自动化框架(一)--概述

    涉及 IntelliJ IDEA Gradle jsoup Commons DbUtils JsonPath Te...

网友评论

      本文标题:Commons DbUtils 与 c3p0 结合使用

      本文链接:https://www.haomeiwen.com/subject/sgdgxftx.html