1、在dao层用dbutils实现事务管理

     //从a--->b帐户转100元
public void transfer() throws SQLException{
Connection conn = null;
try{
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false); QueryRunner runner = new QueryRunner(); //不能给数据源,给数据源的话runner执行完一条sql会自动关闭连接,无法实现事务
String sql1 = "update account set money=money-100 where name='aaa'";
runner.update(conn,sql1); String sql2 = "update account set money=money+100 where name='bbb'";
runner.update(conn,sql2); conn.commit();
}finally{
if(conn!=null){
conn.close();
}
}
}

2、service层和dao层分离实现事务管理

dao层

 public class AccountDao {

     public AccountDao() {
super();
// TODO Auto-generated constructor stub
} 12 private Connection conn;
13 public AccountDao(Connection conn){
14 this.conn = conn;
15 } public void update(Account a){
try{
QueryRunner runner = new QueryRunner();
String sql = "update account set money=? where id=?";
Object params[] = {a.getMoney(),a.getId()};
runner.update(con,sql, params);
}catch (Exception e) {
throw new RuntimeException(e);
}
} public Account find(int id){
try{
QueryRunner runner = new QueryRunner();
String sql = "select * from account where id=?";
return (Account) runner.query(con,sql, id, new BeanHandler(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}

service层

 public void transfer1(int sourceid,int targetid,double money) throws SQLException{

         Connection conn = null;
try{
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false); //开始事务 AccountDao dao = new AccountDao(conn); Account a = dao.find(sourceid); //select
Account b = dao.find(targetid); //select a.setMoney(a.getMoney()-money);
b.setMoney(b.getMoney()+money); dao.update(a); //update dao.update(b);//update conn.commit(); //提交事务
}finally{
if(conn!=null) conn.close();
}
}

3、使用ThreadLocal实现事务管理

dao层

     public void update(Account a){
try{
QueryRunner runner = new QueryRunner();
String sql = "update account set money=? where id=?";
Object params[] = {a.getMoney(),a.getId()};
runner.update(JdbcUtils.getConnection(),sql, params);
}catch (Exception e) {
throw new RuntimeException(e);
}
} public Account find(int id){
try{
QueryRunner runner = new QueryRunner();
String sql = "select * from account where id=?";
return (Account) runner.query(JdbcUtils.getConnection(),sql, id, new BeanHandler(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}

service层

     //用上ThreadLocal的事务管理
public void transfer2(int sourceid,int targetid,double money) throws SQLException{ 4 try{
5 JdbcUtils.startTransaction();
6 AccountDao dao = new AccountDao();
7 Account a = dao.find(sourceid); //select
8 Account b = dao.find(targetid); //select
9 a.setMoney(a.getMoney()-money);
10 b.setMoney(b.getMoney()+money);
11 dao.update(a); //update
12 dao.update(b);//update
13 JdbcUtils.commitTransaction();
14 }finally{
15 JdbcUtils.closeConnection();
}
}

JDBC工具类

 public class JdbcUtils {
private static DataSource ds; 4 private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); //map
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);
}
} public static DataSource getDataSource(){
return ds;
} 21 public static Connection getConnection() throws SQLException{
22 try{
23 //得到当前线程上绑定的连接
24 Connection conn = tl.get();
25 if(conn==null){ //代表线程上没有绑定连接
26 conn = ds.getConnection();
27 tl.set(conn);
28 }
29 return conn;
30 }catch (Exception e) {
31 throw new RuntimeException(e);
32 }
33 } 36 public static void startTransaction(){
37 try{
38 //得到当前线程上绑定连接开启事务
39 Connection conn = tl.get();
40 if(conn==null){ //代表线程上没有绑定连接
41 conn = ds.getConnection();
42 tl.set(conn);
43 }
44 conn.setAutoCommit(false);
45 }catch (Exception e) {
46 throw new RuntimeException(e);
47 }
48 } 51 public static void commitTransaction(){
52 try{
53 Connection conn = tl.get();
54 if(conn!=null){
55 conn.commit();
56 }
57 }catch (Exception e) {
58 throw new RuntimeException(e);
59 }
60 } 62 public static void closeConnection(){
63 try{
64 Connection conn = tl.get();
65 if(conn!=null){
66 conn.close();
67 }
68 }catch (Exception e) {
69 throw new RuntimeException(e);
70 }finally{
71 tl.remove(); //千万注意,解除当前线程上绑定的链接(从threadlocal容器中移除对应当前线程的链接)
72 }
73 }
}

dbutis事务管理的更多相关文章

  1. Spring基于AOP的事务管理

                                  Spring基于AOP的事务管理 事务 事务是一系列动作,这一系列动作综合在一起组成一个完整的工作单元,如果有任何一个动作执行失败,那么事务 ...

  2. spring声明式事务管理总结

    事务配置 首先在/WEB-INF/applicationContext.xml添加以下内容: <!-- 配置事务管理器 --> <bean id="transactionM ...

  3. SpringMVC+MyBatis整合——事务管理

    项目一直没有做事务管理,这几天一直在想着解决这事,今天早上终于解决了.接下来直接上配置步骤. 我们项目采用的基本搭建环境:SpringMVC.MyBatis.Oracle11g.WebLogic10. ...

  4. Spring Boot中的事务管理

    原文  http://blog.didispace.com/springboottransactional/ 什么是事务? 我们在开发企业应用时,对于业务人员的一个操作实际是对数据读写的多步操作的结合 ...

  5. 【Java EE 学习 54】【OA项目第一天】【SSH事务管理不能回滚问题解决】【struts2流程回顾】

    一.SSH整合之后事务问题和总结 1.引入问题:DAO层测试 假设将User对象设置为懒加载模式,在dao层使用load方法. 注意,注释不要放开. 使用如下的代码块进行测试: 会报错:no sess ...

  6. 【Java EE 学习 52】【Spring学习第四天】【Spring与JDBC】【JdbcTemplate创建的三种方式】【Spring事务管理】【事务中使用dbutils则回滚失败!!!??】

    一.JDBC编程特点 静态代码+动态变量=JDBC编程. 静态代码:比如所有的数据库连接池 都实现了DataSource接口,都实现了Connection接口. 动态变量:用户名.密码.连接的数据库. ...

  7. Spring的事务管理

    事务 事务:是逻辑上一组操作,要么全都成功,要么全都失败. 事务特性(ACID) 原子性:事务不可分割 一致性:事务执行的前后,数据完整性保持一致 隔离性:一个事务执行的时候,不应该受到其他事务的打扰 ...

  8. ssh简化后之事务管理

    为了能让大家更好的了解,所以今天跟大家分享整个项目.ps:ssh环境的搭建我就不一一讲解了,请大家参考 http://www.cnblogs.com/zczc1996/p/5842367.html. ...

  9. spring事务管理器设计思想(二)

    上文见<spring事务管理器设计思想(一)> 对于第二个问题,涉及到事务的传播级别,定义如下: PROPAGATION_REQUIRED-- 如果当前没有事务,就新建一个事务.这是最常见 ...

随机推荐

  1. September 14th 2017 Week 37th Thursday

    Don't let the past steal your present. 别让过去悄悄偷走了我们的当下. We take what we can get and make the best of ...

  2. SPL 笔记

    PHP  SPL是指 standard  php library,php标准库. SPL提供了一系列的类和接口,使用这些类和接口,我们可以更加高效.优雅的使用php进行程序设计.   从php5.0开 ...

  3. DOM操作案例之--全选与反选

    全选与反选在表单类的项目中还是很常见的,电商项目中的购物车一定少不了这个功能. 下面我只就用一个简单的案例做个演示吧. <div class="wrap"> <t ...

  4. log4jnet不记录日志的问题解决

    背景:dll文件从别人项目里复制过来的,配置文件是从别的项目里配置过来的.然后就是不写日志. 最后经过搜索原项目,发现需要在AssemblyInfo.cs文件里加一段话, [assembly: log ...

  5. Jinja2 简明使用手册

    @Jinja2 简明使用手册(转载) 介绍 Jinja是基于python的模板引擎,功能比较类似于于PHP的smarty,J2ee的Freemarker和velocity. 运行需求 Jinja2需要 ...

  6. Uva10048 Audiophobia (Floyd)

    题意:有一个无向带权图,求出两点之间路径的最大边权值最小能为多少. 思路:使用floyd算法跑一边以备查询,每一次跑的过程中dp[i][j]=min(dp[i][j],max(dp[i][k],dp[ ...

  7. React-Native 之 index.android.bundle

    问题: index.android.bundle  这个bug 我相信很少同学会遇到,然而就是这个问题,困扰了我跟我的同事多天, 各种方法处理:  进入 android 目录  ./gradlew c ...

  8. ethers.js-4-Contracts

    Contracts A Contract is an abstraction of an executable program on the Ethereum Blockchain. A Contra ...

  9. docker常用命令(二)

    把镜像保存到本为一个文件 docker save -o filename.tar imagename:tag 载入保存在本地的镜像 docker load < filename.tar 或者 d ...

  10. python3 mock

    mock的官网学习备忘录:官网地址https://docs.python.org/3/library/unittest.mock.html#quick-guide 1,安装 python3 unitt ...