Roll back A if B goes wrong. spring boot, jdbctemplate

后端 未结 5 750
自闭症患者
自闭症患者 2020-12-23 13:00

I have a method, \'databaseChanges\', which call 2 operations: A, B in iterative way. \'A\' first, \'B\' last. \'A\' & \'B\' can be Create, U

5条回答
  •  旧巷少年郎
    2020-12-23 13:02

    What you seem to be missing is a TransactionManager. The purpose of the TransactionManager is to be able to manage database transactions. There are 2 types of transactions, programmatic and declarative. What you are describing is a need for a declarative transaction via annotations.

    So what you need to be in place for your project is the following:

    Spring Transactions Dependency (Using Gradle as example)

    compile("org.springframework:spring-tx")
    

    Define a Transaction Manager in Spring Boot Configuration

    Something like this

    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource)
    {
        return new DataSourceTransactionManager(dataSource);
    }
    

    You would also need to add the @EnableTransactionManagement annotation (not sure if this is for free in newer versions of spring boot.

    @EnableTransactionManagement
    public class AppConfig {
    ...
    }
    

    Add @Transactional

    Here you would add the @Transactional annotation for the method that you want to participate in the transaction

    @Transactional
    public void book(String... persons) {
        for (String person : persons) {
            log.info("Booking " + person + " in a seat...");
            jdbcTemplate.update("insert into BOOKINGS(FIRST_NAME) values (?)", person);
        }
    };
    

    Note that this method should be public and not private. You may want to consider putting @Transactional on the public method calling databaseChanges().

    There are also advanced topics about where @Transactional should go and how it behaves, so better to get something working first and then explore this area a bit later:)

    After all these are in place (dependency + transactionManager configuration + annotation), then transactions should work accordingly.

    References

    Spring Reference Documentation on Transactions

    Spring Guide for Transactions using Spring Boot - This has sample code that you can play with

提交回复
热议问题