第03节_加入声明式事务
1、配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 装配数据源 -->
<property name="dataSource" ref="druidDataSource"/>
</bean>
<!-- 开启基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
注意:引入tx名称空间时千万注意名称空间的值
2、创建Service组件
@Service
public class EmpServiceImpl implements EmpService {
@Autowired
private EmpMapper empMapper;
@Override
@Transactional(readOnly = true)
public List<Emp> getAll() {
return empMapper.selectAll();
}
}
3、配置自动扫描的包
<context:component-scan base-package="com.atguigu.ssm.service"/>
4、测试
@Autowired
private EmpService empService;
@Test
public void testTx() {
List<Emp> empList = empService.getAll();
for (Emp emp : empList) {
log.debug("emp = " + emp);
}
}
在框架打印的日志中能够看到事务打开、提交、回滚等操作即可确认声明式事务已生效。
相关日志信息节选: urceTransactionManager - Acquired Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] for JDBC transaction urceUtils - Setting JDBC Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] read-only urceTransactionManager - Switching JDBC Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] to manual commit ing a new SqlSession tering transaction synchronization for SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@babafc2] edTransaction - JDBC Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] will be managed by Spring ctAll - ==> Preparing: select emp_id,emp_name,emp_salary from t_emp ctAll - ==> Parameters: ctAll - <== Total: 15 sing transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@babafc2] action synchronization committing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@babafc2] action synchronization deregistering SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@babafc2] action synchronization closing SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@babafc2] urceTransactionManager - Initiating transaction commit urceTransactionManager - Committing JDBC transaction on Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] urceUtils - Resetting read-only flag of JDBC Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] urceTransactionManager - Releasing JDBC Connection [com.mysql.jdbc.JDBC4Connection@488d1cd7] after transaction