关于ssm整合的时候spring管理事务总是自动提交
在使用spring整合mybatis时,由于不能用到sqlSession来对事物进行管理,必须要利用spring框架对Service进行事务管理。
但是发现自动管理的时候,即使出现了异常,它也还是自动提交,如下:
@Transactional
@Service("studentService")
public class StudentServiceImp implements StudentService {
@Resource(name="studentMapper")
private StudentMapper studentMapper;
@Transactional(propagation=Propagation.REQUIRED)
@Override
public void deleteIds(Long[] ids) {
try {
this.studentMapper.deleteIds(ids); //删除学生操作
System.out.println(1/0); //故意除0造成异常
} catch (Exception e) {
e.printStackTrace();
}
}
}
applicationContext.xml:
<!-- 管理事务的代码 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/> <!-- 这玩意依赖于连接池 -->
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/> //采用注解的方式
明明出现了异常错误,可事务却还是自动提交了,没有发生回滚
通过网上搜寻,如果变成手动管理事务就不会发生这样的事情了。
@Transactional(isolation=Isolation.REPEATABLE_READ,propagation=Propagation.REQUIRED,readOnly=false, rollbackFor=Exception.class)
@Service("studentService")
public class StudentServiceImp implements StudentService {
@Resource(name="studentMapper")
private StudentMapper studentMapper;
@Autowired
private DataSourceTransactionManager transactionManager; //事务管理器
@Override
public void deleteIds(Long[] ids) {
//以下是手动开启事务 发现怎么样都会自动提交,所以干脆用手动提交代码
//1.获取事务定义
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//2.设置事务隔离级别,开启新事务
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
//3.获得事务状态
TransactionStatus status = transactionManager.getTransaction(def);
try {
this.studentMapper.deleteIds(ids);
System.out.println(1/0);
transactionManager.commit(status);
} catch (Exception e) {
System.out.println("出现异常");
transactionManager.rollback(status);
}
}
}
通过手动管理事务,不会发生无法回滚的情况了