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. libc.so.6: cannot open shared object file: No such file or diretory

    环境 centos6.6. 由于误操作 删除了 rm -f /lib64/libc.so.6 导致其他命令不能使用 解决方法: /sbin/sln /lib64/libc-

  2. December 03rd 2016 Week 49th Saturday

    By failing to prepare, you are preparing to fail. 不做准备,那就准备失败吧. How does the case when you had prepa ...

  3. 论文 ClickP4: Towards Modular Programming of P4 小结

    当前P4存在的问题(ClickP4为解决的问题) 1.随着P4程序的规模和复杂性的增加,从零开始开发单片P4程序容易出错,需要相当多的时间和精力去解决,所以网络政策的多样性和动态性使得运营商为了满足要 ...

  4. DOM、JDOM、DOM4J的区别

    dom是解析xml的底层接口之一(另一种是sax)   而jdom和dom4j则是基于底层api的更高级封装    dom是通用的,而jdom和dom4j则是面向Java语言的       DOM 是 ...

  5. VMWare虚拟机下为Windows Server 2012配置静态IP(NAT方式)

    利用VMWare Workstation安装了Windows Server 2012 R2, 对于服务器来说,使用动态分配的IP会很不方便,最好设置为静态IP,此例中虚拟机和主机的网络联接方式为NAT ...

  6. iOS AOP框架Aspects实现原理

    总结: Aspects 是对 类的继承结构isa.mataclass结构的调整和维护:相当于链表的节点插入和删除: 同时使用method Swizzling 对方法统一重定向: 同时使用类似代理的机制 ...

  7. BZOJ2694:Lcm——包看得懂/看不懂题解

    http://www.lydsy.com/JudgeOnline/problem.php?id=2694 Description 对于任意的>1的n gcd(a, b)不是n^2的倍数 也就是说 ...

  8. Entity Framework Code First 遭遇主键自动生成问题

    4.0后就没有去跟踪后面的版本了.现在直接开始用5.0没想到在做User的GURD时就遭遇insert不进数据问题. ISet<User>.Add(user);_context.SaveC ...

  9. CAN--UART的协议转换器

    CAN--UART的协议转换器 //------------------------------------------------------//  CAN <==> UART的协议转换 ...

  10. 50道Java线程面试题(转载)

    1) 什么是线程? 线程是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位.程序员可以通过它进行多处理器编程,你可以使用多线程对运算密集型任务提速.比如,如果一个线程完成 ...