深入分析JavaWeb Item34 -- DBUtils框架学习

birthday date
);
*/

@Test
public void add() throws SQLException {
    //将数据源传递给QueryRunner,QueryRunner内部通过数据源获取数据库连接
    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
    String sql = "insert into users(name,password,email,birthday) values(?,?,?,?)";
    Object params[] = {"孤傲苍狼","123", "gacl@sina.com", new Date()};
    //Object params[] = {"白虎神皇","123", "gacl@sina.com", "1988-05-07"};
    qr.update(sql, params);
}

@Test
public void delete() throws SQLException {

    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
    String sql = "delete from users where id=?";
    qr.update(sql, 1);

}

@Test
public void update() throws SQLException {
    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
    String sql = "update users set name=? where id=?";
    Object params[] = { "ddd", 5};
    qr.update(sql, params);
}

@Test
public void find() throws SQLException {
    QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
    String sql = "select \* from users where id=?";
    Object params[] = {2};
    User user = (User) qr.query(sql, params, new BeanHandler(User.class));
    System.out.println(user.getBirthday());
}

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

/\*\*

* @Method: testBatch
* @Description:批处理
* @Anthor:孤傲苍狼
*
* @throws SQLException
*/
@Test
public void testBatch() throws SQLException {
QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
String sql = “insert into users(name,password,email,birthday) values(?,?,?,?)”;
Object params[][] = new Object[10][];
for (int i = 0; i < 10; i++) {
params[i] = new Object[] { “aa” + i, “123”, “aa@sina.com”,
new Date() };
}
qr.batch(sql, params);
}

//用dbutils完成大数据(不建议用)
/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*

create table testclob
(
id int primary key auto_increment,
resume text
);
**************************************************************************/
@Test
public void testclob() throws SQLException, IOException{
QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());
String sql = “insert into testclob(resume) values(?)”; //clob
//这种方式获取的路径,其中的空格会被使用“%20”代替
String path = QueryRunnerCRUDTest.class.getClassLoader().getResource(“data.txt”).getPath();
//将“%20”替换回空格
path = path.replaceAll(“%20”, " ");
FileReader in = new FileReader(path);
char[] buffer = new char[(int) new File(path).length()];
in.read(buffer);
SerialClob clob = new SerialClob(buffer);
Object params[] = {clob};
runner.update(sql, params);
}
}


### 三、ResultSetHandler接口使用讲解


  该接口用于处理java.sql.ResultSet,将数据按要求转换为另一种形式。   
   ResultSetHandler接口提供了一个单独的方法:Object handle (java.sql.ResultSet .rs)


##### **3.1、ResultSetHandler接口的实现类**


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


##### **3.2、测试dbutils各种类型的处理器**



复制代码
1 package me.gacl.test;
2
3 import java.sql.SQLException;
4 import java.util.Arrays;
5 import java.util.List;
6 import java.util.Map;
7 import me.gacl.util.JdbcUtils;
8 import org.apache.commons.dbutils.QueryRunner;
9 import org.apache.commons.dbutils.handlers.ArrayHandler;
10 import org.apache.commons.dbutils.handlers.ArrayListHandler;
11 import org.apache.commons.dbutils.handlers.ColumnListHandler;
12 import org.apache.commons.dbutils.handlers.KeyedHandler;
13 import org.apache.commons.dbutils.handlers.MapHandler;
14 import org.apache.commons.dbutils.handlers.MapListHandler;
15 import org.apache.commons.dbutils.handlers.ScalarHandler;
16 import org.junit.Test;
17
18 /**
19 * @ClassName: ResultSetHandlerTest
20 * @Description:测试dbutils各种类型的处理器
21 * @author: 孤傲苍狼
22 * @date: 2014-10-6 上午8:39:14
23 *
24 */
25 public class ResultSetHandlerTest {
26
27 @Test
28 public void testArrayHandler() throws SQLException{
29 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
30 String sql = “select * from users”;
31 Object result[] = (Object[]) qr.query(sql, new ArrayHandler());
32 System.out.println(Arrays.asList(result)); //list toString()
33 }
34
35 @Test
36 public void testArrayListHandler() throws SQLException{
37
38 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
39 String sql = “select * from users”;
40 List<Object[]> list = (List) qr.query(sql, new ArrayListHandler());
41 for(Object[] o : list){
42 System.out.println(Arrays.asList(o));
43 }
44 }
45
46 @Test
47 public void testColumnListHandler() throws SQLException{
48 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
49 String sql = “select * from users”;
50 List list = (List) qr.query(sql, new ColumnListHandler(“id”));
51 System.out.println(list);
52 }
53
54 @Test
55 public void testKeyedHandler() throws Exception{
56 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
57 String sql = “select * from users”;
58
59 Map<Integer,Map> map = (Map) qr.query(sql, new KeyedHandler(“id”));
60 for(Map.Entry<Integer, Map> me : map.entrySet()){
61 int id = me.getKey();
62 Map<String,Object> innermap = me.getValue();
63 for(Map.Entry<String, Object> innerme : innermap.entrySet()){
64 String columnName = innerme.getKey();
65 Object value = innerme.getValue();
66 System.out.println(columnName + “=” + value);
67 }
68 System.out.println(“----------------”);
69 }
70 }
71
72 @Test
73 public void testMapHandler() throws SQLException{
74
75 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
76 String sql = “select * from users”;
77
78 Map<String,Object> map = (Map) qr.query(sql, new MapHandler());
79 for(Map.Entry<String, Object> me : map.entrySet())
80 {
81 System.out.println(me.getKey() + “=” + me.getValue());
82 }
83 }
84
85
86 @Test
87 public void testMapListHandler() throws SQLException{
88 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
89 String sql = “select * from users”;
90 List list = (List) qr.query(sql, new MapListHandler());
91 for(Map<String,Object> map :list){
92 for(Map.Entry<String, Object> me : map.entrySet())
93 {
94 System.out.println(me.getKey() + “=” + me.getValue());
95 }
96 }
97 }
98
99 @Test
100 public void testScalarHandler() throws SQLException{
101 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource());
102 String sql = “select count(*) from users”; //[13] list[13]
103 int count = ((Long)qr.query(sql, new ScalarHandler(1))).intValue();
104 System.out.println(count);
105 }
106 }
复制代码


### 四、DbUtils类使用讲解


  DbUtils :提供如关闭连接、装载JDBC驱动程序等常规工作的工具类,里面的所有方法都是静态的。主要方法如下:   
      
   `public static void close(…) throws java.sql.SQLException`: DbUtils类提供了三个重载的关闭方法。这些方法检查所提供的参数是不是NULL,如果不是的话,它们就关闭Connection、Statement和ResultSet。   
   `public static void closeQuietly(…)`: 这一类方法不仅能在Connection、Statement和ResultSet为NULL情况下避免关闭,还能隐藏一些在程序中抛出的SQLEeception。   
   `public static void commitAndCloseQuietly(Connection conn)`: 用来提交连接,然后关闭连接,并且在关闭连接时不抛出SQL异常。   
   p`ublic static boolean loadDriver(java.lang.String driverClassName)`:这一方装载并注册JDBC驱动程序,如果成功就返回true。使用该方法,你不需要捕捉这个异常ClassNotFoundException。


**五、JDBC开发中的事务处理**


  在开发中,对数据库的多个表或者对一个表中的多条数据执行更新操作时要保证对多个更新操作要么同时成功,要么都不成功,这就涉及到对多个更新操作的事务管理问题了。比如银行业务中的转账问题,A用户向B用户转账100元,假设A用户和B用户的钱都存储在Account表,那么A用户向B用户转账时就涉及到同时更新Account表中的A用户的钱和B用户的钱,用SQL来表示就是:


* update account set money=money-100 where name=’A’
* update account set money=money+100 where name=’B’


##### **4.1、在数据访问层(Dao)中处理事务**


  对于这样的同时更新一个表中的多条数据的操作,那么必须保证要么同时成功,要么都不成功,所以需要保证这两个update操作在同一个事务中进行。在开发中,我们可能会在AccountDao写一个转账处理方法,如下:



/**
* @Method: transfer
* @Description:这个方法是用来处理两个用户之间的转账业务
* 在开发中,DAO层的职责应该只涉及到CRUD,
* 而这个transfer方法是处理两个用户之间的转账业务的,已经涉及到具体的业务操作,应该在业务层中做,不应该出现在DAO层的
* 所以在开发中DAO层出现这样的业务处理方法是完全错误的
* @Anthor:孤傲苍狼
*
* @param sourceName
* @param targetName
* @param money
* @throws SQLException
*/
public void transfer(String sourceName,String targetName,float money) 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 = {sourceName};
Object[] paramArr2 = {targetName};
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();
}
}


  然后我们在AccountService中再写一个同名方法,在方法内部调用AccountDao的transfer方法处理转账业务,如下:



public void transfer(String sourceName,String targetName,float money) throws SQLException{
AccountDao dao = new AccountDao();
dao.transfer(sourceName, targetName, money);
}


  上面AccountDao的这个transfer方法可以处理转账业务,并且保证了在同一个事务中进行,但是AccountDao的这个transfer方法是处理两个用户之间的转账业务的,已经涉及到具体的业务操作,应该在业务层中做,不应该出现在DAO层的,在开发中,DAO层的职责应该只涉及到基本的CRUD,不涉及具体的业务操作,所以在开发中DAO层出现这样的业务处理方法是一种不好的设计。


##### **4.2、在业务层(BusinessService)处理事务**


  由于上述AccountDao存在具体的业务处理方法,导致AccountDao的职责不够单一,下面我们对AccountDao进行改造,让AccountDao的职责只是做CRUD操作,将事务的处理挪到业务层(BusinessService),改造后的AccountDao如下:



package me.gacl.dao;

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import me.gacl.domain.Account;
import me.gacl.util.JdbcUtils;

/*account测试表
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values(‘A’,1000);
insert into account(name,money) values(‘B’,1000);
insert into account(name,money) values(‘C’,1000);

*/

/**
* @ClassName: AccountDao
* @Description: 针对Account对象的CRUD
* @author: 孤傲苍狼
* @date: 2014-10-6 下午4:00:42
*
*/
public class AccountDao {

//接收service层传递过来的Connection对象
private Connection conn = null;

public AccountDao(Connection conn){
    this.conn = conn;
}

public AccountDao(){

}

/\*\*

* @Method: update
* @Description:更新
* @Anthor:孤傲苍狼
*
* @param account
* @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 find(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));
}
}


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



package me.gacl.service;

import java.sql.Connection;
import java.sql.SQLException;
import me.gacl.dao.AccountDao;
import me.gacl.domain.Account;
import me.gacl.util.JdbcUtils;

/**
* @ClassName: AccountService
* @Description: 业务逻辑处理层
* @author: 孤傲苍狼
* @date: 2014-10-6 下午5:30:15
*
*/
public class AccountService {

/\*\*

* @Method: transfer
* @Description:这个方法是用来处理两个用户之间的转账业务
* @Anthor:孤傲苍狼
*
* @param sourceid
* @param tartgetid
* @param money
* @throws SQLException
*/
public void transfer(int sourceid,int tartgetid,float money) throws SQLException{
Connection conn = null;
try{
//获取数据库连接
conn = JdbcUtils.getConnection();
//开启事务
conn.setAutoCommit(false);
//将获取到的Connection传递给AccountDao,保证dao层使用的是同一个Connection对象操作数据库
AccountDao dao = new AccountDao(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();
    }catch (Exception e) {
        e.printStackTrace();
        //出现异常之后就回滚事务
        conn.rollback();
    }finally{
        conn.close();
    }
}

}


  程序经过这样改造之后就比刚才好多了,AccountDao只负责CRUD,里面没有具体的业务处理方法了,职责就单一了,而AccountService则负责具体的业务逻辑和事务的处理,需要操作数据库时,就调用AccountDao层提供的CRUD方法操作数据库。


##### **4.3、使用ThreadLocal进行更加优雅的事务处理**


  上面的在businessService层这种处理事务的方式依然不够优雅,为了能够让事务处理更加优雅,我们使用ThreadLocal类进行改造,**ThreadLocal一个容器,向这个容器存储的对象,在当前线程范围内都可以取得出来,向ThreadLocal里面存东西就是向它里面的Map存东西的,然后ThreadLocal把这个Map挂到当前的线程底下,这样Map就只属于这个线程了**


  ThreadLocal类的使用范例如下:



package me.gacl.test;

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);
}

}


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



package me.gacl.util;

import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
* @ClassName: JdbcUtils2
* @Description: 数据库连接工具类
* @author: 孤傲苍狼
* @date: 2014-10-4 下午6:04:36
*
*/
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;
}
}


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



package me.gacl.dao;

import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import me.gacl.domain.Account;
import me.gacl.util.JdbcUtils;
import me.gacl.util.JdbcUtils2;

/*
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values(‘A’,1000);
insert into account(name,money) values(‘B’,1000);
insert into account(name,money) values(‘C’,1000);

*/

/**
* @ClassName: AccountDao
* @Description: 针对Account对象的CRUD
* @author: 孤傲苍狼
* @date: 2014-10-6 下午4:00:42
*
*/
public class AccountDao2 {

public void update(Account account) throws SQLException{

    QueryRunner qr = new QueryRunner();
    String sql = "update account set name=?,money=? where id=?";

文末

技术是没有终点的,也是学不完的,最重要的是活着、不秃。

零基础入门的时候看书还是看视频,我觉得成年人,何必做选择题呢,两个都要。喜欢看书就看书,喜欢看视频就看视频。

最重要的是在自学的过程中,一定不要眼高手低,要实战,把学到的技术投入到项目当中,解决问题,之后进一步锤炼自己的技术。

自学最怕的就是缺乏自驱力,一定要自律,杜绝“三天打鱼两天晒网”,到最后白忙活一场。

高度自律的同时,要保持耐心,不抛弃不放弃,切勿自怨自艾,每天给自己一点点鼓励,学习的劲头就会很足,不容易犯困。

技术学到手后,找工作的时候一定要好好准备一份简历,不要无头苍蝇一样去海投简历,容易“竹篮打水一场空”。好好的准备一下简历,毕竟是找工作的敲门砖。

拿到面试邀请后,在面试的过程中一定要大大方方,尽力把自己学到的知识舒适地表达出来,不要因为是自学就不够自信,给面试官一个好的印象,面试成功的几率就会大很多,加油吧,骚年!

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值