抛出 RuntimeException 会导致事务回滚,但 Exception 不会出现在 spring 启动应用程序中

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

在下面的代码中,抛出 Exception 不会回滚事务,但抛出 RuntimeException 会。

@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. :(

    }
}

我的存储库:

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

Spring开机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

知道为什么会这样吗?

来自docs

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

您可以通过在 @Transactional 注释上指定 rollbackForrollbackForClassName 来覆盖此行为。请参阅上面的文档以获取完整的选项集。