【问题标题】:Update Spring Data create a new record in case of invalid primary key更新 Spring Data 在主键无效的情况下创建新记录
【发布时间】:2019-10-01 01:07:35
【问题描述】:

我在我的应用程序中使用 Spring Data 并调用 "save" Repository 方法来插入新记录或更新现有实体,如果我传递了一个ID(主键)

但我注意到,当我传递一个在我的数据库中不存在的 ID 时插入了一条新记录,我该如何防止这种行为?

在这种情况下我需要抛出一个异常。

谢谢

【问题讨论】:

    标签: spring-boot spring-data-jpa spring-data jhipster


    【解决方案1】:

    save方法的实现如下:

    @Transactional
        public <S extends T> S save(S entity) {
    
            if (entityInformation.isNew(entity)) {
                em.persist(entity);
                return entity;
            } else {
                return em.merge(entity);
            }
        }
    

    所以它会检查它是否是新的。如果它是新的,它会持续存在,否则它会合并。 在这种情况下,您可以使用CrudRepository.existsById(Integer id) 方法来检查它是否存在,因此您可以抛出异常,如下所示:

    例如:

       public void updatePost(Post post) {
            if(!repo.existsById(post.getPostId())){
                throw new ResourceNotFoundException("Resource with given id"+post.getPostId()+" not exists");
            }
            repo.save(post);
        }
    

    【讨论】:

      猜你喜欢
      • 2018-04-15
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-05
      相关资源
      最近更新 更多