Spring Boot JDBC @Transactional won't rollback
Asked Answered
N

1

2

I have implemented a class where i need to insert some data into a database but the insert must rollback if something goes wrong. Once i have performed the insert i throw an exception to test the rollback, but once i check the database, the rows are inserted, which means rollback never happened.

import org.springframework.transaction.annotation.Transactional;
public class SomeClass{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Transactional
    public void insertToDb() throws Exception{
        String sql = "INSERT STUFF"
        jdbcTemplate.update(sql);
        throw new Exception();
    }
}
Nauseous answered 29/9, 2022 at 15:20 Comment(0)
L
8

Referring to the docs for @Transactional:

If no custom rollback rules are configured in this annotation, the transaction will roll back on RuntimeException and Error but not on checked exceptions.

Since Exception is a checked exception, no rollback will be performed by default. You'll either need to throw something that is a (or extends) RuntimeException, or list the exception in the rollbackFor annotation attribute:

@Transactional(rollbackFor = Exception.class)
Lees answered 29/9, 2022 at 15:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.