1.spring事务不会回滚,网上的方法都试过了,没有效果。
2.配置如下:
@RequestMapping(value = "/Save" , method= RequestMethod.POST)
public void departmentSave(Department department, HttpServletResponse response){
departmentService.save(department);
throw new RuntimeException("抛出异常");
}
@Service
@Transactional
public class DepartmentServiceImpl extends BaseServiceImpl implements DepartmentService {
@Autowired
private DepartmentDao deptDao;
......
public void save(Department entity) {
deptDao.save(entity);
}
}
public class BaseDaoImpl implements BaseDao {
private SessionFactory sessionFactory;
protected Class entityClass;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
@Resource
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Session getCurrentSession() {
return this.sessionFactory.getCurrentSession();
}
@SuppressWarnings("rawtypes")
protected Class getEntityClass() {
if (entityClass == null) {
entityClass = (Class) ((ParameterizedType) getClass()
.getGenericSuperclass()).getActualTypeArguments()[0];
}
return entityClass;
}
@Transactional
public Serializable save(T entity) {
return this.getCurrentSession().save(entity);
}
......
}

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
看了看,你对service接口进行事务管理,而不是controller
你抛出异常是在controller,当然不会事务回滚啦
你试试在sevice实现类中,save一下,再抛个异常,看看save成功不成功
ps一下:mysql有两个存储引擎(常用),一个是InnoDB一个是MyISAM,前者支持行级锁,事务,外键,后者不支持
楼上说的没错,spring事务作用于service层,当遇到service方法抛出异常时,事务将回滚。所以你的正确测试实践应该是在service层方法中抛出异常。