简体   繁体   English

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

[英]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. 在下面的代码中抛出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. :(

    }
}

My repository: 我的存储库:

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

Spring boot appliction.properties: 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. 任何RuntimeException都会触发回滚,而任何已检查的Exception都不会。

You can override this behaviour by specifying rollbackFor or rollbackForClassName on the @Transactional annotation. 您可以通过在@Transactional注释上指定rollbackForrollbackForClassName来覆盖此行为。 See above docs for a full set of options. 有关完整选项,请参阅上述文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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