Spring doesn’t directly manage transactions, it comes with a selection of transaction managers, such as: DataSourceTransactionManager, HibernateTransactionManager, JpaTransactionManager etc,.
There are two way to manage transaction in Spring: based on programming or configuration. no matter which way we choose, we always need to define the beans needed:
Here we define a transactionManager using hibernateTransactionManager, and a transaction template:
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="globalRollbackOnParticipationFailure" value="false" />
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="txTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
‘sessionFactory’ bean configuration: http://liguoliang.com/2012/using-spring-jdbc-template/
And now, I’ll show you the the two transaction management ways:
@Autowired private TransactionTemplate txTemplate; /** * Insert new user using transactionTemplate. * @param user */ public void insertUserByTxTemplate(final User user) { txTemplate.execute(new TransactionCallback() { @Override public Void doInTransaction(TransactionStatus txStatus) { try { Session session = sessionFactory.getCurrentSession(); session.save(user); throw new RuntimeException("Exception throwed!"); } catch (Exception e) { txStatus.setRollbackOnly(); } return null; } }); }
Manage transaction using txTemplate.execute().
using annotation
/** * Insert new user using transaction manager. * @param user */ @Transactional(propagation=Propagation.REQUIRED, readOnly=false, rollbackFor=RuntimeException.class) public void insertUser(User user) { Session session = sessionFactory.getCurrentSession(); // SessionFactoryUtils.openSession(sessionFactory); user.setLogin_name(user.getName()); session.save(user); // throw new RuntimeException("RunTimeException for Transaction testing..."); }
If you are using STS(SpringSource tool suite) you can see there is an indicator:
Links:
Spring Transaction – automatic rollback of previous db updates when one db update failes
Spring’s @Transactional does not rollback on checked exceptions
Transaction strategies: Understanding transaction pitfalls
// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.