spring事務管理包含兩種情況,編程式事務、聲明式事務。而聲明式事務又包括基於注解@Transactional和tx+aop的方式。初學中,這里記錄一下自己學習過程中用到的“基於注解的聲明式事務”這種方式
spring beans.xml配置文件中關於事務部分的配置如下:
<!-- 5.事務管理 --> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 事務通知 --> <tx:advice id="txAdivce" transaction-manager="txManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="find*" read-only="false"/> <tx:method name="get*" read-only="false"/> <tx:method name="view*" read-only="false"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.pp.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdivce" pointcut-ref="txPointcut"/> </aop:config> <!-- 開啟事務注解驅動 --> <tx:annotation-driven transaction-manager="txManager" />
首先要開啟事務注解驅動
<!-- 開啟事務注解驅動 --> <tx:annotation-driven transaction-manager="txManager" />
在aop切面配置節中聲明 在哪個包中使用事務,我的例子中聲明的是 com.pp.service 包中
<aop:config> <aop:pointcut expression="execution(* com.pp.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdivce" pointcut-ref="txPointcut"/> </aop:config>
聲明在哪種方法中使用事務
<!-- 事務通知 --> <tx:advice id="txAdivce" transaction-manager="txManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="find*" read-only="false"/> <tx:method name="get*" read-only="false"/> <tx:method name="view*" read-only="false"/> </tx:attributes> </tx:advice>
如果在<tx:method /> 節中沒有聲明在程序中使用的方法的話,需要在該方法使用@Transactional注解,如下:
@Transactional//事務注解,需要在spring 配置文件中開啟事務注解驅動 public void add(SysRole role, String[] permissionIds) { this.insert(role); int a = permissionIds.length; List<SysRoleAuthorize> lst = role.getLstAuthorize(); if (lst != null) { for (SysRoleAuthorize entity : lst) { entity.setfId(UUID.randomUUID().toString()); entity.setfObjecttype(1); entity.setfObjectid(role.getfId()); daoAuthorize.insert(entity); } } }
如果不在方法上面使用@Transactional注解,那么需要在tx:advice節中增加如下黃色背景的方法聲明
<!-- 事務通知 --> <tx:advice id="txAdivce" transaction-manager="txManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="find*" read-only="false"/> <tx:method name="get*" read-only="false"/> <tx:method name="view*" read-only="false"/> </tx:attributes> </tx:advice>
這里的name=“add*”對應的就是java代碼中的add方法