[英]JpaRepository - delete method - inform that entity does not exist
During delete operation, can a JpaRepository inform me, that entity I want to remove does not exists ?在删除操作期间, JpaRepository可以通知我,我要删除的那个实体不存在吗?
I know that delete methods doesn't returns boolean value, and also doesn't throws Exceptions .我知道 delete 方法不会返回布尔值,也不会抛出Exceptions 。
I also know that I can just simply do exists() or findOne() and then perform delete, but I'm just curious.我也知道我可以简单地执行 exists() 或 findOne() 然后执行删除,但我只是好奇。
Is there any way to force this?有什么办法可以强制执行此操作吗?
I'm using Spring Boot 1.5.1.我正在使用 Spring Boot 1.5.1。 Sample code below:
示例代码如下:
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);
}
Starting from Spring Data JPA (>=1.7.x), we can use the derived delete
or remove
query.从 Spring Data JPA (>=1.7.x) 开始,我们可以使用 派生的
delete
或remove
查询。 It can return the number of entities deleted or what all entities are deleted.它可以返回删除的实体数或所有实体被删除的数量。
Using it we can update our code as:使用它我们可以将我们的代码更新为:
public interface EventRepository extends JpaRepository<Event, Long> {
long deleteByTitle(String title);
}
and we can throw an exception if the entity doesn't exist.如果实体不存在,我们可以抛出异常。
public HttpStatus deleteEventByTitle(String eventTitle) {
long numOfEntriesDeleted = eventRepository.deleteByTitle(eventTitle);
if(numOfEntriesDeleted != 1){
return HttpStatus.NOT_FOUND;
}
return HttpStatus.OK;
}
According to the spec this is not possible and I am not aware of a functionality like this.根据规范,这是不可能的,我不知道这样的功能。
I know that when working with Cassandra and Datastax you can check wasApplied()
.我知道在使用 Cassandra 和 Datastax 时,您可以检查
wasApplied()
。
The only way around would be to implement your own deleteOrThrowException
-method and throw an exception in case you didn't find the entity.唯一的解决方法是实现您自己的
deleteOrThrowException
方法,并在找不到实体时抛出异常。
In order to achieve this you could add a为了实现这一点,你可以添加一个
@Query("select count(event)>0 from Event e where eventTitle := eventTitle")
public boolean existsByTitle(String eventTitle);
You can simply check if it exists before deleting it:您可以在删除它之前简单地检查它是否存在:
// Check if the ID is available
if (deviceRepository.existsById(id)) {
deviceRepository.deleteById(id);
//returnObject.setMessage("Deleted successfully !!");
} else {
//returnObject.setMessage("The ID is not found");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.