Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Boot JDBC @Transactional won't rollback

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();
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading