Spring @Transaction(readonly = true)上下文在进程中间向DB提交数据

时间:2017-05-02 10:46:57

标签: java spring hibernate transactions

我正在进行一项任务,以使代码具有事务性。我有关于只读事务的问题,而我在互联网上找不到任何单一建议都没有用。 (Spring和hibernate集成项目)

这是我的只读交易方法

@Transactional(propagation=Propagation.REQUIRES_NEW, readOnly=true 
,rollbackFor=Exception.class)
    public void 
editInternationalExportConsigment(InternationalExportConsignmentFormWrapper 
exportConssi (){}

在此方法中,发生了翻译过程。进程从DB获取(选择)数据并设置为Object

  Contact contact =inquiry.loadCustomerContactById(consignmentVO.getCustomerContactId().intValue()); 

    if (contact != null && contact.getCity() != null) {
          consignment.setOrgin(contact.getCity().getCountry());
          consignment.setUniqueOriginCountry((contact.getCity().getCountry()!=null)?contact.getCity().getCountry().getId():null);
          consignment.setOrginCity(contact.getCity());
    }

中间没有任何更新或插入查询,只有选择。但是在此代码段执行结束时,它将数据提交给DB(无论设置为setter方法的值是否会持久存储到DB中)

有人可以告诉我这里发生了什么错误。你的反馈意见会很多。

1 个答案:

答案 0 :(得分:0)

经过繁琐的研究,我找到了答案。在我们的项目中有两个会话工厂正在运行。此外,它还使用spring OpenSessionInViewFilter 来避免“延迟初始化”问题。 OpenSessionInViewFilter 已将flushMode设置为Auto。由于 OpenSessionInViewFilter 在整个过程中保持将hibernate会话绑定到线程,它将覆盖事务hibernate会话对象,一旦我启动新事务就会创建它。因此,即使我保留了flushmode for事务范围为'COMMIT'它通过声明为 OpenSessionInViewFilter 的属性覆盖 AUTO 属性。

当flushMode为AUTO时,hibernate会将脏对象刷新到DB。 Read this for understand hibernate data flushin

作为解决方案,我在我的交易方法中手动将刷新模式更改为'COMMIT'

感谢大家的回复和评论。 :)