在删除操作期间,JpaRepository能否通知我,我要删除的实体不存在 ?
我知道删除方法不会返回 boolean 值,也不会抛出异常。
我也知道我可以简单地执行exists()或findOne(),然后执行删除,但我只是好奇。
有什么办法可以强制执行此操作吗?
我正在使用 Spring Boot 1.5.1。 示例代码如下:
public HttpStatus deleteEventByTitle(String eventTitle) {
try {
eventRepository.deleteByTitle(eventTitle);
} catch (EntityNotFoundException e) { // just showing what I want to do
return HttpStatus.NOT_FOUND;
}
return HttpStatus.OK;
}
public interface EventRepository extends JpaRepository<Event, Long> {
void deleteByTitle(String title);
}
最佳答案
从 Spring Data JPA (>=1.7.x) 开始,我们可以使用 derived 删除
或删除
查询。它可以返回删除的实体数量或所有实体被删除的数量。
使用它我们可以将代码更新为:
public interface EventRepository extends JpaRepository<Event, Long> {
long deleteByTitle(String title);
}
如果实体不存在,我们可以抛出异常。
public HttpStatus deleteEventByTitle(String eventTitle) {
long numOfEntriesDeleted = eventRepository.deleteByTitle(eventTitle);
if(numOfEntriesDeleted != 1){
return HttpStatus.NOT_FOUND;
}
return HttpStatus.OK;
}
关于java - JpaRepository - 删除方法 - 通知实体不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43641145/