spring中使用事務有兩種方式,一種是程式設計式,一種是聲明式。
程式設計式事務
程式設計式事務管理使用TransactionTemplate或者直接使用底層的PlatformTransactionManager。對于程式設計式事務管理,spring推薦使用TransactionTemplate。類似下面的代碼,注入transactionTemplate後,執行execute方法,方法參數是一個TransactionCallback的匿名實作,TransactionCallbackWithoutResult是一個抽象類,實作了TransactionCallback接口。
//在需要使用的類中注入transactionTemplate
@Autowired
private TransactionTemplate transactionTemplate;
//不關心結果的事務執行方式
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
//TODO db操作 業務代碼
}
});
//關心結果的事務執行方式
Object object= transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
//doSomething()為業務代碼
Object object = doSomething();
return object;
}
});
聲明式事務
聲明式事務是基于AOP之上的。其本質是在執行方法前後進行攔截,在方法開始之前建立或者加入一個事務,在執行完目标方法之後根據執行情況送出或者復原事務。如下的代碼隻需要在方法上面加入注解@Transactional就可以進行事務操作。以删除促銷為例,我們删除促銷的時候會删除促銷關聯的産品,隻有這兩個操作都執行成功才算成功,是以整合成一個事務。
//聲明式事務
@Transactional
public Integer deletePromotion(Integer id) {
//查詢一下
Promotion promotion = getPromotion(id);
//删除促銷
int ret = promotionDao.deletePromotion(promotion.getId());
//再删除産品
if(ret > 0){
promotionProductDao.deletePromotionProductByPromotionId(promotion.getId());
}
return ret;
}
總結
spring中使用事務有兩種方式,一種是程式設計式事務,一種是聲明式事務。程式設計式事務推薦使用TransactionTemplate,實作TransactionCallback接口,需要編碼實作;聲明式事務隻需要在函數增加注解@Transactional,無需任何配置,代碼入侵較小,使用AOP原理,推薦使用聲明式事務,在應用啟動類上記得加上@EnableTransactionManagement注解喲。
轉自springboot或spring中使用程式設計式事務和聲明式事務
更加詳細的解釋請移步:Spring程式設計式和聲明式事務執行個體講解