I have doubts about handling transaction exceptions. To clearly state my problem, I would like to show my configuration:
<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>
Active Transaction Class:
@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); } }
My doubts are in the addNewCustomer method. I set rollbackFor = { Throwable.class } .
How it works?
I also need to explicitly handle the exception, for example:
@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; }
Actually, I threw an exception by deleting the column from the client table, but this exception was not caught in the try-catch block, rather I can catch this exception from the managed bean where I called addNewCustomer .
source share