- 声明式事务:AOP
- 编程式事务:需要在代码中,进行事务的管理
为什么需要事务?
为了保证事务的ACID原则
- 原子性
- 一致性
- 隔离性
- 持久性
如果不配置事务,可能会存在数据提交不一致的情况
如果我们不在spring中去配置声明式事务,我们就需要在代码中手动配置事务
事务在项目的开发中十分重要,涉及到数据的一致性和完整性问题,不容马虎。
一xml式的配置
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="TxAdvice" transaction-manager="transactionManager">
<!--给那些方法配置事务-->
<!--配置事务的传播特性 propagation-->
<tx:attributes>
<tx:method name="selectUser" read-only="true"/>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<!-- <tx:method name="*"/>-->
</tx:attributes>
</tx:advice>
<!--配置事务切入-->
<aop:config >
<aop:pointcut id="pointCut" expression="execution(* com.yf.mapper.*.*(..))"/>
<aop:advisor advice-ref="TxAdvice" pointcut-ref="pointCut"/>
</aop:config>
注解式的配置
<!--配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
然后在需要事务性的方法前面加上@Transactional即可
public interface UserMapper {
@Transactional
public List<User> selectUser();
public int add(@Param("user") User user);
public int delete(@Param("id") String id);
}
如果所有的方法都需要事务性,直接在类的前面加注解。