简体   繁体   中英

Throwing a RuntimeException causes the transaction to rollback, but Exception doesn't in a spring boot app

In the following code throwing an Exception doesn't rollback the transaction, but throwing a RuntimeException does.

@Service
public class HelloService {    
    @Autowired
    protected CustomerRepository repository;
    @Transactional
    public void run() throws Exception {
        repository.save(new Customer("Jack", "Bauer"));
        throw new RuntimeException("Kabooom!!!"); //Transaction is rolled back. Database is empty :)
        //throw new Exception("Kabooom!!!"); //If this is used instead the records are inserted into the database. :(

    }
}

My repository:

public interface CustomerRepository extends CrudRepository<Customer, Long> {
}

Spring boot appliction.properties:

# DataSource settings: set here configurations for the database connection
spring.datasource.url = jdbc:mysql://localhost/hobbadb
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driverClassName = com.mysql.jdbc.Driver    
# Specify the DBMS
spring.jpa.database = MYSQL    
# Show or not log for each sql query
spring.jpa.show-sql = true    
# Hibernate settings are prefixed with spring.jpa.hibernate.*
spring.jpa.hibernate.ddl-auto = update
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.hibernate.hbm2ddl.auto= create-drop

Any ideas why this is happening?

From the docs :

Any RuntimeException triggers rollback, and any checked Exception does not.

You can override this behaviour by specifying rollbackFor or rollbackForClassName on the @Transactional annotation. See above docs for a full set of options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM