【问题标题】:Spring refresh entity if db state has changed如果数据库状态已更改,则弹簧刷新实体
【发布时间】:2017-09-05 10:39:40
【问题描述】:

我有一个 Springboot 应用程序和一个带有大量 PL/SQL 过程的 Oracle DB,它们一直在改变 DB 的状态。 所以现在我想改变一个加载的实体并保存它。如果 entitymanager 的 entitystate 和 db 的状态相等,则一切正常。但在某些情况下,它们并不相等。因此,如果我加载一个实体并进行一些更改并在此过程中进行一些更改,那么一个 PL/SQL 过程会更改数据库表。如果我保存实体,我当然会得到一个 Execption。所以我试图捕捉异常,然后在捕捉块中我想在保存之前刷新实体。但我仍然得到一个例外。交易没有完成吗?我该如何处理这个问题? 我希望示例代码能解释一下。

    @RestController
    @RequestMapping("/*")
    public class FacadeController {

     ...

     @ResponseStatus(HttpStatus.OK)
     @RequestMapping( value= "/test4" , method=RequestMethod.GET)
     public String test4(){

        Unit unit = unitSvice.loadUnit(346497519L);   

        List<UnitEntry> entries = unit.getEntries();      

        for (UnitEntry g : entries) {
          if (g.getUnitEntryId == 993610345L) {
            g.setTag("AA");
            g.setVersion(g.getVersion() + 1);
            g.setstatus("SaveOrUpdate");
          }
        }    

        //<-- DB Table changed entity managed by entitymanger and DB Table 
        //    are no langer equal. 

        try {      
         unitSvice.updateUnit(unit , false);
        }catch(DataAccessException | IllegalArgumentException e) {
         unitSvice.updateUnit(unit , true);
        }

       ...

     }
   }


@Service("unitSvice")
public class UnitSvice {

  @Autowired
  private UnitDao repoUnit;

  @Transactional
  public Unit loadUnit(Long _id) {
    Unit unit = repoUnit.findOne(_id);   
    return unit;
  }

  @Transactional
  public void updateUnit(Unit unit, boolean _withrefrsh )  {
   if(_withrefrsh) {
     getEntityManager().refresh(unit.getId());
   }
    repoUnit.save(unit);
  }

}

我希望,任何人都可以帮助我。

谢谢

【问题讨论】:

  • 你能说明你有什么样的错误吗?

标签: java spring spring-boot spring-data-jpa spring-transactions


【解决方案1】:

是的,问题是 ..当您调用 load all 方法时,该方法是事务性方法,当您从该方法返回时,实体与会话/实体管理器分离。因此,接下来您将尝试保留分离的对象。这就是为什么你得到例外。 所以可能你可以使用 session.update() 或 session.merge() 将新的更新保存到数据库中。

【讨论】:

  • 感谢您的回复。 session.update() 和 entityManager 的刷新也不起作用。但是 entityManager.find(Unit.class, id) 有效。 find 方法返回更新后的 db 实体。所以我合并并保存它们。它似乎有效,但我不确定这是否是一个好习惯。
猜你喜欢
  • 2014-03-28
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2011-02-26
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多