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

前端之家收集整理的这篇文章主要介绍了java – 抛出RuntimeException导致事务回滚,但Exception不在spring启动应用程序中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的代码中抛出异常不会回滚事务,但会抛出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 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

任何想法为什么会这样?

解决方法

docs

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

您可以通过在@Transactional注释上指定rollbackFor或rollbackForClassName来覆盖此行为.有关完整选项,请参阅上述文档.

原文链接:https://www.f2er.com/java/126005.html

猜你在找的Java相关文章