xml 代码
- <beans>
- ...
- <bean id="myTxManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
- <property name="sessionFactory" ref="mySessionFactory"/>
- </bean>
- <bean id="myProductService" class="product.ProductServiceImpl">
- <property name="transactionManager" ref="myTxManager"/>
- <property name="productDao" ref="myProductDao"/>
- </bean>
- </beans>
java 代码
- public class ProductServiceImpl implements ProductService {
- private PlatformTransactionManager transactionManager;
- private ProductDao productDao;
- public void setTransactionManager(PlatformTransactionManager transactionManager) {
- this.transactionManager = transactionManager;
- }
- public void setProductDao(ProductDao productDao) {
- this.productDao = productDao;
- }
- public void increasePriceOfAllProductsInCategory(final String category) {
- TransactionTemplate transactionTemplate = new TransactionTemplate(this.transactionManager);
- transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
- transactionTemplate.execute(
- new TransactionCallbackWithoutResult() {
- public void doInTransactionWithoutResult(TransactionStatus status) {
- List productsToChange = productDAO.loadProductsByCategory(category);
- ...
- }
- }
- );
- }
- }
本文介绍了一个使用Spring框架进行事务管理的具体实例。通过XML配置文件定义了事务管理器和业务服务类,并展示了如何在业务逻辑中利用TransactionTemplate来确保数据操作的原子性。此方法适用于需要在多个数据操作间保持一致性的场景。
4543

被折叠的 条评论
为什么被折叠?



