关于java:Spring-事务

22次阅读

共计 4795 个字符,预计需要花费 12 分钟才能阅读完成。

Spring 事务

个性

ACID: 原子性, 一致性, 隔离性, 持久性。

事务是一个不可分割的操作,其中的过程要么全副胜利要么全副失败。一旦实现后会对立提交来保障一致性。

不同的事务处理对立数据是隔离的, 避免数据的损坏。事务的后果会被永恒的保留。

分类

  • 编程式事务

将事务管理代码嵌到业务办法中来管制事务的提交和回滚

毛病:必须在每个事务操作业务逻辑中蕴含额定的事务管理代码

  • 申明式事务

将事务管理代码从业务办法中分离出来,以申明的形式来实现事务管理。

将事务管理作为横切关注点,通过 aop 办法模块化。

编程式事务

public class UserMapperImpl1 extends SqlSessionDaoSupport implements UserMapper{
    private final PlatformTransactionManager transactionManager;
    public UserMapperImpl1(PlatformTransactionManager transactionManager) {this.transactionManager = transactionManager;}
    @Override
    public List<User> selectUser() {return getSqlSession().getMapper(UserMapper.class).selectUser();}

    @Override
    public int addUser(User user) {
        int a=0;
        TransactionStatus txStatus =
                transactionManager.getTransaction(new DefaultTransactionDefinition());
        try{getSqlSession().getMapper(UserMapper.class).addUser(user);
            getSqlSession().getMapper(UserMapper.class).deleteUser(10);
        }catch (Exception e){transactionManager.rollback(txStatus);
            throw e;
        }
        return a;
    }
  /* 此处和上述统一  
//        TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
//        a = transactionTemplate.execute(txStatus -> {//            getSqlSession().getMapper(UserMapper.class).addUser(user);
//            getSqlSession().getMapper(UserMapper.class).deleteUser(10);
//            return null;
//        });
    @Override
    public int deleteUser(Integer id) {return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
    }
}

申明式事务

罕用两种传播方式:

  • propagation_requierd:如果以后没有事务,就新建一个事务,如果已存在一个事务中,退出到这个事务中,这是最常见的抉择。
  • propagation_nested:如果以后存在事务,则在嵌套事务内执行。如果以后没有事务,则执行与 propagation_required 相似的操作。

XML 配置:

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.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/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--    引入 SQL 工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!--        关联 mybatis 配置 -->
        <property name="typeAliases" value="com.spring.pojo.User"/>
        <!--        扫描包 -->
        <property name="mapperLocations" value="classpath:com/spring/mapper/*.xml"></property>
    </bean>
    <!--    注册 sqlSessionTemplate , 关联 sqlSessionFactory-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!-- 利用结构器注入 -->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
<!--    配置申明式事务 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="userMapper" class="com.spring.mapper.UserMapperImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

    <!-- 配置事务告诉 -->
    <!-- 联合 AOP 实现事务的织入 -->
    <!-- 配置事务告诉 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 给那些办法配置事务 -->
        <!-- 配置事务的流传个性:new -->
        <tx:attributes>
            <tx:method name="addUser" propagation="REQUIRED"/>
            <tx:method name="deleteUser" propagation="REQUIRED"/>
            <tx:method name="updateUser" propagation="REQUIRED"/>
            <tx:method name="selectUser" read-only="true"/>
<!--            <tx:method name="*" propagation="REQUIRED"/>-->
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="txPointCut" expression="execution(* com.spring.mapper.UserMapper.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    </aop:config>
</beans>

JAVA 类:

public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> selectUser() {int a1 = getSqlSession().getMapper(UserMapper.class).addUser(new User(12,"wxn1"));
        return getSqlSession().getMapper(UserMapper.class).selectUser();}

    @Override
    public int addUser(User user) {System.out.println("新增开始");
        int a = getSqlSession().getMapper(UserMapper.class).addUser(user);
        System.out.println("新增完结");
        return a;
    }

    @Override
    public int deleteUser(@Param(value = "id") Integer id) {System.out.println("删除开始");
        int a1 = getSqlSession().getMapper(UserMapper.class).addUser(new User(12,"wxn1"));
        int a2 = getSqlSession().getMapper(UserMapper.class).deleteUser(id);
        System.out.println("删除完结");
        return a2;
    }
}

测试类:

public void selectUser() {ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
//        userMapper.addUser(new User(8,"丽丽 1"));
//        userMapper.deleteUser(10);
        for (User user : userMapper.selectUser()) {System.out.println(user);
        }
    }

正文完
 0