Ram*_*sar 0 spring-data spring-data-jpa spring-boot jhipster
我在我的应用程序中使用 Spring Data 并调用“save” Repository 方法来插入新记录或更新现有实体,如果我传递ID (Primary key)。
但是我注意到,当我传递一个在我的数据库中不存在的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);
}
}
Run Code Online (Sandbox Code Playgroud)
所以它会检查它是否是新的。如果它是新的,它会持续存在,否则它会合并。在这种情况下,您可以使用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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
765 次 |
最近记录: |