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();
}
}
CodePudding user response:
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)