【发布时间】:2012-05-28 03:10:10
【问题描述】:
我目前正在学习 Spring + Hibernate 的集成,到目前为止我正在让它工作。但是我遇到了不想在流程结束时提交事务的情况,因为我只想查看生成的 sql 语句以进行测试和调试。
我已经在我的休眠属性中添加了 false,但是它仍然无法正常工作。
如果使用Spring处理hibernate事务可以实现吗?因为在hibernate中使用传统事务是有可能的,只要不调用session.commit()方法就不会保存所有的更新和插入;
目前我的服务层有此代码:
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true) 公共类 EmployeeServiceImpl{
@Autowired
private EmployeeDao employeeDao
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void saveEmployee(Employee employee){
// count the number of employee in the database
int n = employeeDao.getEmployeeCount();
// lets say it should print 10 here
System.out.println("number of employee before inserting : " + n);
// insert to employee
employeeDao.saveEmployee(employee);
// then count the employee after inserting
n = employeeDao.getEmployeeCount();
// then it should print 11 here after inserting new employee
System.out.println("number of employee after inserting : " + n);
/* Then Dont commit insert!!!
*/
}
}
Dao 层代码:
public EmployeeDaoImpl implements EmployeeDao{
@Autowired
public void saveEmployee(Employee employee){
sessionFactory.getCurrentSession.save(employee);
}
public int getEmployeeCount(){
String count = sessionFactory.getCurrentSesion.createQuery("select count(emp.employeeId) from Employee emp")
.list().get(0).toString;
return Integer.valueOf(count);
}
}
但是这里发生的是它确实提交了事务!但我不想仅仅为了测试和调试目的而提交事务。
我也试过 @Transactional(传播 = Propagation.SUPPORTS,只读 = 假) 代替 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
但是这里发生的是它没有提交事务,但是员工的数量也没有增加。
所以,我期望在这里发生的是在插入员工表之前计算员工人数。然后插入员工表并再次计算员工人数,因此它将增加 1。但是在过程结束时,我不想提交该插入!
你们有什么想法吗?
如果有任何帮助,我将不胜感激! 谢谢!
【问题讨论】:
标签: hibernate spring-mvc transactions set autocommit