【问题标题】:Spring update all entity with saveSpring使用保存更新所有实体
【发布时间】:2021-02-20 01:37:57
【问题描述】:

大家早上好, 我试图通过它的 id 完全更新一个实体,我正在使用一个从 JPA 扩展的存储库,我认为只要让它保存系统就会破坏旧的系统,但事实并非如此,我收到了这个错误:

org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

我尝试过使用 entityManager.flush();但我得到一个错误:

javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'flush' call

我找到了更新数据库字段的选项,但我真正想要的是完全粉碎数据库行,有那么复杂吗?我该怎么做?我应该删除记录并重新创建它吗? (我不相信,因为我们正在生成两个过渡,但我不知道它是否正常)

我把负责修改实体的代码放上去:

 @PostMapping ("/ user")
    public ResponseEntity postUser (@RequestBody User user) {
        Map <Object, Object> model = new HashMap <> ();
        entityManager.flush ();
        User newUSer = userRepository.saveAndFlush (user);
        model.put ("user", newUSer);
        return ok (model);
    }

谢谢!

【问题讨论】:

    标签: spring-boot hibernate jpa repository


    【解决方案1】:

    好的,经过一些测试帐户后,我发现了如何使其正常工作,但我做错了,因为当我编写此代码时,我得到了正确的结果:

    @PostMapping ("/ user")
        public ResponseEntity postUser (@RequestBody User user) {
    
            Map <Object, Object> model = new HashMap <> ();
    
            AtomicReference <ResponseEntity> responseEntity = new AtomicReference <> ();
            Optional <User> optionalUser = Optional.of (userRepository.findById (user.getId ()). Get ());
    
            OptionalConsumer.of (optionalUser) .ifPresent (u -> {
                u.setPassword (user.getPassword ());
                userRepository.save (u);
                model.put ("user", u);
                responseEntity.set (ok (model));
            }). ifNotPresent (() -> responseEntity.set (notFound (). build ()));
    
            return responseEntity.get ();
        }
    

    所以我要做的是在User模型中创建一个merge方法来修改参数传递的数据并正确保存(我对更好的方法持开放态度,可能有更多推荐的工作方式,请告诉我!)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2018-04-20
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2013-04-03
      • 2019-02-09
      相关资源
      最近更新 更多