如何使用Spring MVC在休眠中将自动提交设置为false



我目前正在学习Spring + Hibernate的集成,到目前为止,我正在让它工作。但是我遇到了我不想在进程结束时提交事务的情况,因为我只想查看生成的 sql 状态以进行测试和调试。

我已经在我的休眠属性中添加了 false,但它仍然不起作用。

如果使用 Spring 处理休眠事务,

是否可以实现? 因为在休眠中使用传统事务时,有可能,只是不要调用session.commit()方法,所有更新和插入都不会保存;

目前我的服务层有以下代码:

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)public class 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!!!
*/
}

}

道层代码:

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 = Propagation.SUPPORTS, readOnly = false)而不是@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)

但这里发生的事情是它不会提交事务,但是员工计数也不会增加。

因此,我期望在这里发生的是在插入员工表之前计算员工人数。然后插入到员工表中并再次计算员工人数,因此它将增加 1。但是在过程结束时,我不想提交那个插入!

你有什么想法吗?

我将非常感谢任何帮助!谢谢!

要进行测试,请使用 Spring 测试框架。它为您处理自动事务回滚。如果你正在寻找别的东西,你将不得不更具体。你的问题虽然充满了细节,但对你真正想做的事情相当模糊。你只是经常使用"测试"和"调试"这样的词。这些词对不同的人可能意味着很多不同的东西。

最新更新