事务
一:有时候几个步骤加起来是为了完成某件事,但是需要保证其中的每个步骤都需要正确,才能保证执行结果的正确;如果某一个步骤出错,就不能执行结果,所以需要将所有的步骤看成一个整体,有异常就不执行;
二:ACID:原子性,一致性,隔离性,持久性;
三:声明式事务,编程式事务;
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/> <property name="username" value="root"/> <property name="password" value="root"/> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="configLocation" value="classpath:mybatisConfig.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <bean id="userMapper" class="com.nbg.mapper.impl.UserMapperImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <!--配置声明式事务--> <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="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--配置事务切入--> <aop:config> <aop:pointcut id="pit" expression="execution(* com.nbg.mapper.impl.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pit"/> </aop:config> </beans>
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper { @Override public List<User> selectUser() { delUser(1); return getSqlSession().getMapper(UserMapper.class).selectUser(); } @Override public void delUser(int id) { getSqlSession().getMapper(UserMapper.class).delUser(id); } }