我对事务的异常处理有疑问。为了清楚地说明我的问题,我想显示我的配置:
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionInterceptor" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager" />
<property name="transactionAttributeSource">
<bean class="org.springframework.transaction.annotation.AnnotationTransactionAttributeSource" />
</property>
</bean>
<bean id="baseService" abstract="true">
<property name="daoProvider" ref="daoProvider" />
</bean>
<bean id="customerService" parent="transactionInterceptor">
<property name="target">
<bean class="com.edfx.adb.service.CustomerService" parent="baseService" />
</property>
</bean>
<bean id="daoProvider" class="com.edfx.adb.dao.provider.DaoProvider">
<property name="customerDao" ref="customerDao" />
</bean>
<bean id="customerDao" class="com.edfx.adb.dao.CustomerDao">
<constructor-arg value="#{T(com.edfx.adb.persist.entity.Customer)}" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>活动事务处理分类为:
@Transactional
public class CustomerService extends BaseService implements ICustomerService {
@Transactional(readOnly = true)
public Customer getCustomerById(String id) {
return getDaoProvider().getCustomerDao().getCustomerById(id);
}
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
public void addNewCustomer(CustomerDTO customerDTO) {
Customer customer = new Customer();
customer.setCustomerId(customerDTO.getCustomerId());
customer.setCustomerName(customerDTO.getCustomerName());
customer.setActive(customerDTO.isActive());
getDaoProvider().getCustomerDao().save(customer);
}
}我的疑虑在于addNewCustomer方法。我已经设置了rollbackFor = { Throwable.class }。
它怎麽工作?
另外,我是否需要显式地处理异常,如:
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = { Throwable.class })
public boolean addNewCustomer(CustomerDTO customerDTO) {
Customer customer = new Customer();
customer.setCustomerId(customerDTO.getCustomerId());
customer.setCustomerName(customerDTO.getCustomerName());
customer.setActive(customerDTO.isActive());
try {
getDaoProvider().getCustomerDao().save(customer);
} catch (Throwable throwable) {
return false;
}
return true;
}我通过从customer表中删除一列强制创建了一个异常,但该异常不是在try-catch块中捕获的,而是可以从调用了addNewCustomer方法的托管bean捕获该异常。
发布于 2012-12-15 02:26:56
这是Spring文档的摘录
在其默认配置中,Spring Framework的事务基础结构代码仅在发生运行时未检查异常的情况下标记要回滚的事务;即,当抛出的异常是RuntimeException的实例或子类时。(默认情况下,错误也会导致回滚)。从事务性方法引发的检查异常不会在默认配置中导致回滚。
您设置了rollbackFor = Throwable.class,现在Spring将回滚任何异常/错误。默认情况下,不管我们喜欢与否,Spring只会对RuintimeException进行回滚,否则就会提交
发布于 2012-12-15 02:03:31
Spring框架只抛出RuntimeExceptions,从技术上讲,您永远不需要捕获任何异常。
https://stackoverflow.com/questions/13883966
复制相似问题