1 package learnFromBilibili.util; 2 3 import java.sql.SQLException; 4 5 /** 6 * 和事务管理相关的工具类,它包含开启事务、提交事务、回滚事务和释放事务 7 * @author tony fan 8 */ 9 public class TransactionManager { 10 11 private ConnectionUtils connectionUtils; 12 13 public void setConnectionUtils(ConnectionUtils connectionUtils) { 14 this.connectionUtils = connectionUtils; 15 } 16 17 /** 18 * 开启事务 19 */ 20 public void beginTransaction(){ 21 try { 22 connectionUtils.getThreadConnection().setAutoCommit(false); 23 } catch (SQLException e) { 24 e.printStackTrace(); 25 } 26 } 27 28 /** 29 * 提交事务 30 */ 31 public void commit(){ 32 try { 33 connectionUtils.getThreadConnection().commit(); 34 } catch (SQLException e) { 35 e.printStackTrace(); 36 } 37 } 38 39 /** 40 * 回滚事务 41 */ 42 public void rollback(){ 43 try { 44 connectionUtils.getThreadConnection().rollback(); 45 } catch (SQLException e) { 46 e.printStackTrace(); 47 } 48 } 49 50 /** 51 * 释放事务 52 */ 53 public void release(){ 54 try { 55 connectionUtils.getThreadConnection().close(); 56 connectionUtils.removeConnection(); 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 } 60 } 61 62 }