事物管理用于出错回滚等
1基于xml的配置
applicationContext.xml中声明jdbc事物管理器并配置数据源datasource c3p0等
还需引入namespace 否则会报错且没提示,
aop
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-xsd"
tx
xmlns:tx="http://www.springframework.org/schema/tx"
<!--jdbc事物管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean>配置事务通知
<!--配置事物通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*"/> </tx:attributes> </tx:advice>配置事物切面
<!--配置事物切面--> <aop:config> <!--配置切点--> <aop:pointcut id="serviceMethod" expression="execution(* service.StudentService*.*(..))"/> <!--配置事物通知--> <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/> </aop:config>expression="execution(* service.*.*(..))" 返回值 包 类 方法名 (..)任意参数 ×任意值
2注解式
在applicationContext.xml中加入
<tx:annotation-driven transaction-manager="transactionManager"/>然后在相应的地方即service层添加@transactional即可service层发生事物管理
总结各有优缺点
1 service多的情况下比较好不用每个service写@transactional注解