【附源码】Spring Boot实战系列——五、事务抽象

304 阅读1分钟

【附源码】Spring Boot实战系列——一、配置内存数据库H2
【附源码】Spring Boot实战系列——二、配置多个数据源(H2数据库)
【附源码】Spring Boot实战系列——三、配置多个数据源(Mysql数据库)
【附源码】Spring Boot实战系列——四、日志管理
【附源码】Spring Boot实战系列——五、事务抽象
【附源码】Spring Boot实战系列——六、货币存数据库的处理

引入依赖

  • 数据库H2依赖
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
  • Java数据库连接JDBC依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

代码结构

声明式事务

@Service
public class FooServiceImpl implements FooService {
    @Autowired
    private JdbcTemplate jdbcTemplate;


    @Override
    @Transactional
    public void insertRecord() {
        jdbcTemplate.execute("insert into foo(value) values('ddd')");
    }


    @Override
    @Transactional(rollbackFor=RollbackException.class)
    public void insertThenRollback() throws RollbackException{
        jdbcTemplate.execute("insert into foo(value) values('eee')");


        // 触发事务回滚
        throw new RollbackException();
    }


    @Override
    public void invokeInsertThenRollback() throws RollbackException {
        // 对象内部调用不触发事务回滚
        insertThenRollback();
    

编程式事务

    private void run_programmaric_transaction() {
        log.info("count before transaction: {}", getCount());
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                jdbcTemplate.execute("insert into foo(value) values('ccc')");
                log.info("count doing transaction: {}", getCount());
                transactionStatus.setRollbackOnly();
            }
        });


        log.info("count after transaction: {}", getCount());
    }

运行结果

源码下载地址

github.com/qiulanzhu/S…