事务:要么都成功,要么都失败。例子:支付宝交易。
acid原则。
11直接移植10的代码
spring-11-transaction:
UserMapper(增加两个接口)
package com.Li.mapper;
import com.Li.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
//添加一个用户
public int addUser(User user);
//删除一个用户
public int deleteUser(int id);
}
UserMapper.xml:(配置两个接口sql)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Li.mapper.UserMapper">
<!--sql-->
<select id="selectUser" resultType="user">
select * from mybatis.user
</select>
<insert id="addUser" parameterType="user">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<delete id="deleteUser" parameterType="int">
deletes from mybatis.user where id = #{id}
</delete>
</mapper>
把UserMapperImpl的接口实现类也重写一下。避免报错。
UserMapperImpl2:(生成一个User,用来插入)
package com.Li.mapper;
import com.Li.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
//继承SqlSessionDaoSupport,不需要创建sqlSession了,可以直接用
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectUser() {
User user = new User(5, "王桑", "1232132");
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.addUser(user);
mapper.deleteUser(5);
return mapper.selectUser();
}
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
@Override
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
在spring-dao.xml原有的基础上,增加下面的内容。(配置事务)
<!-- 配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--结合AOP实现事务的织入-->
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给name的方法配置事务-->
<!--配置事务传播特性propagation。默认为REQUIRED-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置事务切入,也就是作用在那些方法上-->
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.Li.mapper.*.*(..))"/>
<!--把什么切到什么里-->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
直接测试:
报错,同时也没有插入成功。