SSM 配置事务管理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chenbetter1996/article/details/83792865

事务管理

事务是一或多个对数据库的操作的组合,要么所有操作都执行,要么都不执行(原子性)
在Spring中可以通过注解来实现事务管理,原理是AOP

业务实现

// dao接口
@Autowired
private UserMapper userMapper; 
    
@Override
@Transactional
public void register(String phone, String password, byte roleType) {
	user.setPhone(phone);
	user.setPassword(password);
    user.setRoleType(roleType);
    // 开始为用户在tb_user和tb_userinfo表注册
    userMapper.insertUser(user);
    userMapper.insertUserinfo(user);
    log.info("注册成功");
}

这是业务层实现的一个方法,里面有两个dao调用,使用了 @Transactional 表示这个是事务


配置

<!-- JDBC事务管理器 -->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <property name="dataSource" ref="dataSource"/>
   </bean>

   <!-- 启用annotation注解方式事务管理 -->
   <tx:annotation-driven transaction-manager="transactionManager"/>

一般来说,service和dao层归spring容器管,springmvc容器管controller和view/web层。所以这个代码应该放在spring的applicationContext.xml配置文件中更好。

猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/83792865
今日推荐