我对事务的异常处理有疑问。为了清楚地说明我的问题,我想展示我的配置:
<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;
}
我通过从客户表中删除一列强制创建了一个异常,但是该异常没有在 try-catch 块中捕获,而是我可以从调用该addNewCustomer
方法的托管 bean 中捕获该异常。