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

tsx81429  论坛元老 | 2024-8-4 18:12:19 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1013|帖子 1013|积分 3039

public class AccountDao {
  1. //接收service层传递过来的Connection对象
  2. private Connection conn = null;
  3. public AccountDao(Connection conn){
  4.     this.conn = conn;
  5. }
  6. public AccountDao(){
  7. }
  8. /\*\*
复制代码
* @Method: update
* @Description:更新
* @Anthor:孤傲苍狼
*
* @param account
* @throws SQLException
*/
public void update(Account account) throws SQLException{
  1.     QueryRunner qr = new QueryRunner();
  2.     String sql = "update account set name=?,money=? where id=?";
  3.     Object params[] = {account.getName(),account.getMoney(),account.getId()};
  4.     //使用service层传递过来的Connection对象操作数据库
  5.     qr.update(conn,sql, params);
  6. }
  7. /\*\*
复制代码
* @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));
}
}
  1.   接着对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 {
  1. /\*\*
复制代码
* @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);
  1.         source.setMoney(source.getMoney()-money);
  2.         target.setMoney(target.getMoney()+money);
  3.         dao.update(source);
  4.         //模拟程序出现异常让事务回滚
  5.         int x = 1/0;
  6.         dao.update(target);
  7.         //提交事务
  8.         conn.commit();
  9.     }catch (Exception e) {
  10.         e.printStackTrace();
  11.         //出现异常之后就回滚事务
  12.         conn.rollback();
  13.     }finally{
  14.         conn.close();
  15.     }
  16. }
复制代码
}
  1.   程序经过这样改造之后就比刚才好多了,AccountDao只负责CRUD,里面没有具体的业务处理方法了,职责就单一了,而AccountService则负责具体的业务逻辑和事务的处理,需要操作数据库时,就调用AccountDao层提供的CRUD方法操作数据库。
  2. ##### **4.3、使用ThreadLocal进行更加优雅的事务处理**
  3.   上面的在businessService层这种处理事务的方式依然不够优雅,为了能够让事务处理更加优雅,我们使用ThreadLocal类进行改造,**ThreadLocal一个容器,向这个容器存储的对象,在当前线程范围内都可以取得出来,向ThreadLocal里面存东西就是向它里面的Map存东西的,然后ThreadLocal把这个Map挂到当前的线程底下,这样Map就只属于这个线程了**
  4.   ThreadLocal类的使用范例如下:
复制代码
package me.gacl.test;
public class ThreadLocalTest {
  1. public static void main(String[] args) {
  2.     //得到程序运行时的当前线程
  3.     Thread currentThread = Thread.currentThread();
  4.     System.out.println(currentThread);
  5.     //ThreadLocal一个容器,向这个容器存储的对象,在当前线程范围内都可以取得出来
  6.     ThreadLocal<String> t = new ThreadLocal<String>();
  7.     //把某个对象绑定到当前线程上 对象以键值对的形式存储到一个Map集合中,对象的的key是当前的线程,如: map(currentThread,"aaa")
  8.     t.set("aaa");
  9.     //获取绑定到当前线程中的对象
  10.     String value = t.get();
  11.     //输出value的值是aaa
  12.     System.out.println(value);
  13. }
复制代码
}
  1.   使用使用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 {
  1. private static ComboPooledDataSource ds = null;
  2. //使用ThreadLocal存储当前线程中的Connection对象
  3. private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
  4. //在静态代码块中创建数据库连接池
  5. static{
  6.     try{
  7.         //通过代码创建C3P0数据库连接池
  8.         /\*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);*/
  1.         //通过读取C3P0的xml配置
复制代码
真题分析、进阶学习条记、最新讲解视频、实战项目源码、学习路线大纲
详情关注公中号【编程进阶路】
文件创建数据源,C3P0的xml配置文件c3p0-config.xml必须放在src目录下
//ds = new ComboPooledDataSource();//使用C3P0的默认配置来创建数据源
ds = new ComboPooledDataSource(“MySQL”);//使用C3P0的命名配置来创建数据源
  1.     }catch (Exception e) {
  2.         throw new ExceptionInInitializerError(e);
  3.     }
  4. }
  5. /\*\*
复制代码
* @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;
}
  1. /\*\*
复制代码
* @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);
}
}
  1. /\*\*
复制代码
* @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);
}
}
  1. /\*\*
复制代码
* @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);
}
}
  1. /\*\*
复制代码
* @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);
}
}
  1. /\*\*
复制代码
* @Method: getDataSource
* @Description: 获取数据源
* @Anthor:孤傲苍狼
* @return DataSource
*/
public static DataSource getDataSource(){
//从数据源中获取数据库毗连
return ds;
}
}
  1.   对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 {
  1. public void update(Account account) throws SQLException{
  2.     QueryRunner qr = new QueryRunner();
  3.     String sql = "update account set name=?,money=? where id=?";
  4.     Object params[] = {account.getName(),account.getMoney(),account.getId()};
  5.     //JdbcUtils2.getConnection()获取当前线程中的Connection对象
  6.     qr.update(JdbcUtils2.getConnection(),sql, params);
  7. }
  8. public Account find(int id) throws SQLException{
  9.     QueryRunner qr = new QueryRunner();
  10.     String sql = "select \* from account where id=?";
  11.     //JdbcUtils2.getConnection()获取当前线程中的Connection对象
  12.     return (Account) qr.query(JdbcUtils2.getConnection(),sql, id, new BeanHandler(Account.class));
  13. }
复制代码
}
  1.   对AccountService进行改造,service层不再需要传递数据库连接Connection给Dao层,改造后的AccountService如下:
复制代码
package me.gacl.service;
import java.sql.SQLException;
import me.gacl.dao.AccountDao2;
import me.gacl.domain.Account;
import me.gacl.util.JdbcUtils2;
public class AccountService2 {
  1. /\*\*
复制代码
* @Method: transfer
* @Description:在业务层处置惩罚两个账户之间的转账问题
* @Anthor:孤傲苍狼
*
* @param sourceid
* @param tartgetid
* @param money
* @throws SQLException
*/
public void transfer(int sourceid,int tartgetid,float money) throws SQLException{
try{
//开启事务,在业务层处置惩罚事务,包管dao层的多个操作在同一个事务中进行
JdbcUtils2.startTransaction();
AccountDao2 dao = new AccountDao2();
  1.         Account source = dao.find(sourceid);
  2.         Account target = dao.find(tartgetid);
  3.         source.setMoney(source.getMoney()-money);
  4.         target.setMoney(target.getMoney()+money);
  5.         dao.update(source);
  6.         //模拟程序出现异常让事务回滚
  7.         int x = 1/0;
  8.         dao.update(target);
  9.         //SQL正常执行之后提交事务
  10.         JdbcUtils2.commit();
  11.     }catch (Exception e) {
  12.         e.printStackTrace();
  13.         //出现异常之后就回滚事务
  14.         JdbcUtils2.rollback();
  15.     }finally{
  16.         //关闭数据库连接
  17.         JdbcUtils2.close();
  18.     }
  19. }
复制代码
}
  1.   这样在service层对事务的处理看起来就更加优雅了。ThreadLocal类在开发中使用得是比较多的,**程序运行中产生的数据要想在一个线程范围内共享,只需要把数据使用ThreadLocal进行存储即可。**
  2. ##### **4.4、ThreadLocal + Filter 处理事务**
  3.   上面介绍了JDBC开发中事务处理的3种方式,下面再介绍的一种使用ThreadLocal + Filter进行统一的事务处理,这种方式主要是使用过滤器进行统一的事务处理,如下图所示:
  4.  ![这里写图片描述](https://img-blog.csdn.net/20151228130525970)
  5. **1、编写一个事务过滤器TransactionFilter**
  6. 代码如下:
复制代码
package me.gac.web.filter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import me.gacl.util.JdbcUtils;
/**
* @ClassName: TransactionFilter
* @Description:ThreadLocal + Filter 统一处置惩罚数据库事务
* @author: 孤傲苍狼
* @date: 2014-10-6 下午11:36:58
*
*/
public class TransactionFilter implements Filter {
  1. @Override
  2. public void init(FilterConfig filterConfig) throws ServletException {
  3. }
  4. @Override
  5. public void doFilter(ServletRequest request, ServletResponse response,
  6.         FilterChain chain) throws IOException, ServletException {
  7.     Connection connection = null;
  8.     try {
  9.         //1、获取数据库连接对象Connection
  10.         connection = JdbcUtils.getConnection();
  11.         //2、开启事务
  12.         connection.setAutoCommit(false);
  13.         //3、利用ThreadLocal把获取数据库连接对象Connection和当前线程绑定
  14.         ConnectionContext.getInstance().bind(connection);
  15.         //4、把请求转发给目标Servlet
  16.         chain.doFilter(request, response);
  17.         //5、提交事务
  18.         connection.commit();
  19.     } catch (Exception e) {
  20.         e.printStackTrace();
  21.         //6、回滚事务
  22.         try {
  23.             connection.rollback();
  24.         } catch (SQLException e1) {
  25.             e1.printStackTrace();
  26.         }
  27.         HttpServletRequest req = (HttpServletRequest) request;
  28.         HttpServletResponse res = (HttpServletResponse) response;
  29.         //req.setAttribute("errMsg", e.getMessage());
  30.         //req.getRequestDispatcher("/error.jsp").forward(req, res);
  31.         //出现异常之后跳转到错误页面
  32.         res.sendRedirect(req.getContextPath()+"/error.jsp");
  33.     }finally{
  34.         //7、解除绑定
  35.         ConnectionContext.getInstance().remove();
  36.         //8、关闭数据库连接
  37.         try {
  38.             connection.close();
  39.         } catch (SQLException e) {
  40.             e.printStackTrace();
  41.         }
  42.     }
  43. }
  44. @Override
  45. public void destroy() {
  46. }
复制代码
}
  1.   我们在TransactionFilter中把获取到的数据库连接使用ThreadLocal绑定到当前线程之后,在DAO层还需要从ThreadLocal中取出数据库连接来操作数据库,因此需要编写一个ConnectionContext类来存储ThreadLocal,ConnectionContext类的代码如下:
复制代码
package me.gac.web.filter;
import java.sql.Connection;
/**
* @ClassName: ConnectionContext
* @Description:数据库毗连上下文
* @author: 孤傲苍狼
* @date: 2014-10-7 上午8:36:01
*
*/
public class ConnectionContext {
  1. /\*\*
复制代码
* 构造方法私有化,将ConnectionContext设计成单例
*/
private ConnectionContext(){
  1. }
  2. //创建ConnectionContext实例对象
  3. private static ConnectionContext connectionContext = new ConnectionContext();
  4. /\*\*
复制代码
* @Method: getInstance
* @Description:获取ConnectionContext实例对象
* @Anthor:孤傲苍狼
*
* @return
*/
public static ConnectionContext getInstance(){
return connectionContext;
}
  1. /\*\*
复制代码
* @Field: connectionThreadLocal
* 使用ThreadLocal存储数据库毗连对象
*/
private ThreadLocal connectionThreadLocal = new ThreadLocal();
  1. /\*\*
复制代码
* @Method: bind
* @Description:利用ThreadLocal把获取数据库毗连对象Connection和当前线程绑定
* @Anthor:孤傲苍狼
*
* @param connection
*/
public void bind(Connection connection){
connectionThreadLocal.set(connection);
}
  1. /\*\*
复制代码
* @Method: getConnection
* @Description:从当前线程中取出Connection对象
* @Anthor:孤傲苍狼
*
* @return
*/
public Connection getConnection(){
return connectionThreadLocal.get();
}
  1. /\*\*
复制代码
* @Method: remove
* @Description: 排除当前线程上绑定Connection
* @Anthor:孤傲苍狼
*
*/
public void remove(){
connectionThreadLocal.remove();
}
}
  1.   在DAO层想获取数据库连接时,就可以使用ConnectionContext.getInstance().getConnection()来获取,如下所示:
复制代码
package me.gacl.dao;
import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import me.gac.web.filter.ConnectionContext;
import me.gacl.domain.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 AccountDao3 {
  1. public void update(Account account) throws SQLException{
  2.     QueryRunner qr = new QueryRunner();
  3.     String sql = "update account set name=?,money=? where id=?";
  4.     Object params[] = {account.getName(),account.getMoney(),account.getId()};
  5.     //ConnectionContext.getInstance().getConnection()获取当前线程中的Connection对象
  6.     qr.update(ConnectionContext.getInstance().getConnection(),sql, params);
  7. }
  8. public Account find(int id) throws SQLException{
  9.     QueryRunner qr = new QueryRunner();
  10.     String sql = "select \* from account where id=?";
  11.     //ConnectionContext.getInstance().getConnection()获取当前线程中的Connection对象
  12.     return (Account) qr.query(ConnectionContext.getInstance().getConnection(),sql, id, new BeanHandler(Account.class));
  13. }
复制代码
}
  1.   businessService层也不用处理事务和数据库连接问题了,这些统一在TransactionFilter中统一管理了,businessService层只需要专注业务逻辑的处理即可,如下所示:
复制代码
package me.gacl.service;
import java.sql.SQLException;
import me.gacl.dao.AccountDao3;
import me.gacl.domain.Account;
public class AccountService3 {
  1. /\*\*
复制代码
* @Method: transfer
* @Description:在业务层处置惩罚两个账户之间的转账问题
* @Anthor:孤傲苍狼
*
* @param sourceid
* @param tartgetid
* @param money
* @throws SQLException
*/
public void transfer(int sourceid, int tartgetid, float money)
throws SQLException {
AccountDao3 dao = new AccountDao3();
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);
}
}
  1.   Web层的Servlet调用businessService层的业务方法处理用户请求,需要注意的是:调用businessService层的方法出异常之后,继续将异常抛出,这样在TransactionFilter就能捕获到抛出的异常,继而执行事务回滚操作,如下所示:
复制代码
package me.gacl.web.controller;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import me.gacl.service.AccountService3;
public class AccountServlet extends HttpServlet {
最后

编程底子的初级开发者,计算机科学专业的门生,以及平时没怎么利用过数据结构与算法的开发职员希望复习这些概念为下次技术面试做准备。或者想学习一些计算机科学的基本概念,以优化代码,提高编程技能。这份条记都是可以作为参考的。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

tsx81429

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表