![](/img/trans.png)
[英]Spring Transaction doesn't Rollback at RuntimeException in @Transactional method
[英]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 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
任何想法為什么會這樣?
來自文檔 :
任何RuntimeException都會觸發回滾,而任何已檢查的Exception都不會。
您可以通過在@Transactional
注釋上指定rollbackFor
或rollbackForClassName
來覆蓋此行為。 有關完整選項,請參閱上述文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.