1、编程式事务:TransactionTemplate
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
jdbcTemplate.execute("INSERT INTO FOO (ID, BAR) VALUES (1, 'aaa')");
log.info("COUNT IN TRANSACTION: {}", getCount());
transactionStatus.setRollbackOnly();
}
});
执行execute方法,参数是回滚类型
2、声明式事务
利用aop在我们的目标方法上面做了一层封装(对我们的类做了一个代理),利用事务模板对方法进行操作。
开始事务注解的方式:@EnableTransactionManagement
如果在方法上面加上事务注解,方法内部之间调用是没有效果的。
package geektime.spring.data.declarativetransactiondemo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class FooServiceImpl implements FooService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
@Transactional
public void insertRecord() {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('AAA')");
}
@Override
@Transactional(rollbackFor = RollbackException.class)
public void insertThenRollback() throws RollbackException {
jdbcTemplate.execute("INSERT INTO FOO (BAR) VALUES ('BBB')");
throw new RollbackException();
}
@Override
public void invokeInsertThenRollback() throws RollbackException {
insertThenRollback();
}
}
invokeInsertThenRollback方法执行没有事务效果。因为aop是对我们的类做了一层代理
我们只有调用代理类事务才会生效,方法内部直接调用不会经过代理类。
本文介绍了Spring中的编程式和声明式事务管理。编程式事务通过TransactionTemplate执行事务回调,在事务中执行SQL插入并设置回滚状态。声明式事务则利用AOP在目标方法上创建代理,通过@EnableTransactionManagement开启事务管理。注意,方法内部调用带有事务注解的方法不会生效,必须通过代理类调用才能触发事务。
656

被折叠的 条评论
为什么被折叠?



