Update Spring 数据在主键无效的情况下创建一条新记录

Update Spring Data create a new record in case of invalid primary key

我在我的应用程序中使用 Spring 数据并调用 "save" 存储库方法 插入 一个新的如果我传递 ID(主键).

,则记录或 更新 现有实体

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

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

谢谢

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);
    }