編程式事務:需要手動的開啟事務,提交。
聲明式事務:Spring 中的事務是利用AOP 編程思想,底層是通過動態代理的方式(cglib動態代理),cglib 底層是通過asm字節碼框架,實現動態的事務功能,不許要手動的開啟,提交
以下例子是通過編程事務實現手動事務來對比Spirng 中的AOP封裝手動事務:
例1:手動事務的begin() , commit() ,rollback()
測試數據庫:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.hella.thread.transaction"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!-- 開啟事物注解 --> <!-- 1. 數據源對象: C3P0連接池 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb"></property> <property name="user" value="root"></property> <property name="password" value="123456"></property> </bean> <!-- 2. JdbcTemplate工具類實例 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 3.配置事務 --> <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> </beans>
表結構:cat 表 id ,cat_age,cat_name 三個字段
CREATE TABLE `cat` ( `id` int(11) NOT NULL AUTO_INCREMENT, `cat_age` varchar(255) DEFAULT NULL, `cat_name` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
Service 層:
public interface UserService { public void addUser(); }
@Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public void addUser() { //添加到數據庫 System.out.println("開始添加"); userDao.add(1, "tom", "12"); //service 層沒有事務的情況下,很容易出現問題,不能保證原子性 } }
dao 層:
@Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public void add(int id, String age, String name) { String sql = "INSERT INTO cat(id,cat_age,cat_name) VALUES(?,?,?);"; int updateResult = jdbcTemplate.update(sql, id, age, name); System.out.println("updateResult:" + updateResult); } }
程序的入口:
public class App { public static void main(String[] args) { ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext( "spring.xml"); UserService userService = (UserService) classPathXmlApplicationContext.getBean("userServiceImpl"); userService.addUser(); } }
這是沒有配置事務的情況的下,當往數據庫插入多條數據的時候,一個數據有問題,其他數據也可以插入,不能保證原子性,所以我們需要添加事務:
AOP log:額外的功能
@Component // 放入到Spring容器中 @Aspect // 定義切面類 公共的log部分 public class AspectLog { // aop 編程的通知 前置通知 后置通知 環繞通知 異常通知 運行通知 @Before("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )") public void before() { System.out.println("前置通知。。。。"); } @After("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )") // 若是包名寫的不對,或是類名不對:[Xlint:invalidAbsoluteTypeName]error
public void after() { System.out.println("后置通知。。。"); } @Around("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )") public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { System.out.println("環繞通知 proceed前 。。。"); proceedingJoinPoint.proceed(); System.out.println("環繞通知 proceed后。。。"); // 異常則proceed后就不會執行 } @AfterReturning("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )") public void returning() { System.out.println("運行通知 。。。"); } @AfterThrowing("execution (* com.hella.thread.transaction.service.UserService.addUser(..) )") public void afterThrowing() { System.out.println("異常通知"); } }
編寫事務類:包含begin() commit() rollback()
@Component public class TransactionUtils { @Autowired private DataSourceTransactionManager dataSourceTransactionManager; // 開啟事務 public TransactionStatus begin() { TransactionStatus transaction = dataSourceTransactionManager.getTransaction(new DefaultTransactionAttribute()); return transaction; } // 提交事務 public void commit(TransactionStatus transaction) { dataSourceTransactionManager.commit(transaction); } // 回滾事務 public void rollback(TransactionStatus transaction) { dataSourceTransactionManager.rollback(transaction); } }
service 層的方法需要加入事務:
@Service public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; @Autowired private TransactionUtils transactionUtils; @Override public void addUser() { TransactionStatus transactionStatus = null; try { transactionStatus = transactionUtils.begin(); // 添加到數據庫 System.out.println("開始添加"); userDao.add(1, "tom", "12"); int i = 1 / 0; if (transactionStatus != null) { transactionUtils.commit(transactionStatus); } } catch (Exception e) { e.printStackTrace(); // if (transactionStatus != null) { // transactionUtils.rollback(transactionStatus); // } } finally { // 在catch 里面回滾也可以,但是catch 回滾后異常通知就接收不到了 if (transactionStatus != null) { transactionStatus.rollbackToSavepoint(transactionStatus); } } } }
這樣編程式事務就OK 了