事务:要么都成功,要么都失败。例子:支付宝交易。
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
selectUser(); -
- //添加一个用户
- public int addUser(User user);
-
- //删除一个用户
- public int deleteUser(int id);
- }
UserMapper.xml:(配置两个接口sql)
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
- <mapper namespace="com.Li.mapper.UserMapper">
-
-
- <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
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>
-
-
-
- <tx:advice id="txAdvice" transaction-manager="transactionManager">
-
-
- <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>
直接测试:
报错,同时也没有插入成功。