Day23SSM之Spring事务注解***

Spring事务管理-转账-注解

使用注解事务管理:
1.重新复制 dao层的代码 service层的代码 (给实现类上添加@Repository @Service) 注入的时候使用@Autowried自动注入
2.重新编写一个bean3.xml (保留: 加载db.properties , DataSource , JdbcTemplate , 平台事务管理器其他xml配置删除); 先配置包扫描
再该xml中重新添加 注解驱动 (支持注解方式的事务)
3.给AccountServiceImpl 类上添加一个@Transactional注解即可
4.测试AccountService 的transfer方法 看看是否能够控制事务

applicationContext.xml

    <!--1.要在bean.xml中创建spring的平台事务管理器  (DataSourceTransactionManager   )  注入dataSource-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--2.配置注解驱动-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

AccountServiceImpl

@Service
//@Transactional(isolation = Isolation.REPEATABLE_READ ,propagation = Propagation.REQUIRED ,timeout = -1)
public class AccountServiceImpl implements IAccountService{
    
    
    @Autowired
    IAccountDao dao ;
    @Transactional(isolation = Isolation.REPEATABLE_READ ,propagation = Propagation.REQUIRED ,timeout = -1)
    @Override
    public void translate(String from, String to, double money) {
    
    
        //创建AccountDaoImpl
        //AccountDaoImpl dao = new AccountDaoImpl();
        //调用方法

        dao.translateOut(from,money);
        System.out.println(1/0); //断电
        dao.translateIn(to,money);
        System.out.println("--translate");
    }
}

猜你喜欢

转载自blog.csdn.net/u013621398/article/details/109030572