问题描述
我有这样的事情:
@Service
@Transactional
public class ServiceA {
@Autowired
SomeDAO1 dao1;
@Autowired
ServiceB serviceB;
public void methodServiceA() {
serviceB.someMethodThatRunsInsertIntoDB();
dao1.anotherMethodThatRunsInsertIntoDB();
}
}
@Service
@Transactional
public class ServiceB {
@Autowired
Dao2 dao2;
public void someMethodThatRunsInsertIntoDB() {
dao2.insertXXX();
}
}
我的问题是:如果 serviceB.someMethodThatRunsInsertIntoDB()
执行成功但 dao1.anotherMethodThatRunsInsertIntoDB()
抛出异常,则 serviceB
所做的更改> 不会回滚.我需要回滚这些更改,以防 dao1.anotherMethodThatRunsInsertIntoDB()
中发生异常.我该怎么做?
My problem is: if serviceB.someMethodThatRunsInsertIntoDB()
executes sucessfully but dao1.anotherMethodThatRunsInsertIntoDB()
throw an exception, the changes made by serviceB
are not rolled back. I need to rollback those changes in case an exception occur in dao1.anotherMethodThatRunsInsertIntoDB()
. How can I do this?
//已编辑
spring-servlet.xml 中的事务配置
Transaction configuration in spring-servlet.xml
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
如果一个 dao 使用 EntityManager 而另一个 dao 使用 JdbcTemplate 与 DB 交互,是否相关?
Is it relevant if one dao uses an EntityManager and the other dao uses JdbcTemplate to interact with DB?
//UPDATE -- EntityManager 配置
//UPDATE -- EntityManager configuration
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
</bean>
</property>
推荐答案
您需要传递带有检查异常类型的 rollbackFor
参数.似乎默认情况下,spring 仅在未检查的异常上回滚.更多详情:Spring 事务:在异常或 Throwable 上回滚
you need to pass rollbackFor
parameter with type of your checked exception. It seems that spring rollbacks only on unchecked exceptions by default. More details: Spring transaction: rollback on Exception or Throwable
这篇关于Spring事务不回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!