本文共 1653 字,大约阅读时间需要 5 分钟。
1:在配置文件中开启对@Transactional的支持
<tx:annotation-driven transaction-manager="txManager"/>
2:在类或者方法上配置@Transactional
3:@Transactional后面可以跟属性配置,如下:
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
1:事务传播设置是 PROPAGATION_REQUIRED
2:事务隔离级别是 ISOLATION_DEFAULT
4:事务超时默认是依赖于事务系统的,或者事务超时没有被支持。
5:任何 RuntimeException 将触发事务回滚,但是任何 checked Exception 将不触发事务回滚
2:直接使用一个 PlatformTransactionManager 实现
如果你选择编程式事务管理,Spring小组推荐你采用第一种方法(即使用 TransactionTemplate)。第二种方法类似使用JTA的 UserTransaction API (除了异常处理简单点儿)。
使用 TransactionTemplate:TransactionTemplate 采用与Spring中别的摸板同样的方法,使用回调机制,将应用代码从样板式的资源获取和释放代码中解放出来,不再有大量的try/catch/finally/try/catch代码块。同样,和别的模板类一样,TransactionTemplate 类的实例是线程安全的。 使用TransactionTemplate示例如下: 使用 PlatformTransactionManager 你也可以直接使用PlatformTransactionManager的实现来管理事务。只需通过bean引用简单地传入一个 PlatformTransactionManager 实现,然后使用 TransactionDefinition 和 TransactionStatus 对象,你就可以启动一个事务,提交或回滚。
使用 PlatformTransactionManager示例如下: 直接使用统一的PlatformTransactionManager java代码: -
- PlatformTransactionManager txManager = (PlatformTransactionManager)
- ctx.getBean("txManager");
-
- DefaultTransactionDefinition td = new DefaultTransactionDefinition();
- td.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED);
-
- TransactionStatus status = txManager.getTransaction(td);
- try {
-
- new JdbcTemplate(ds).execute("insert into tbl_user (uuid,name) values('"+um1.getUuid()+"','"+um1.getName()+"')");
-
- txManager.commit(status);
- }catch (Exception e) {
-
- txManager.rollback(status);
- }
转载地址:http://gblvi.baihongyu.com/