Spring-data:阻止更新

问题描述 投票:0回答:1

我正在寻找一种方法来防止使用spring-data更新对象。我找到了一些关于此的主题,但没有一个有解决方案。

我有一个可以创建和阅读的对象。而已。我不想支持修改/更新。我自己管理/生成数据库ID。

我很想使用org.springframework.data.repository.Repository接口(或JpaRepository / CrudRepository,如果我能以某种方式改变<S extends T> S save(S entity);逻辑以防止更新),因为我喜欢干净的findBy ...界面符号。

到目前为止我发现的最佳解决方案是实现Persistable并覆盖isNew(…)以始终返回true。但这很糟糕,因为如果它是只读的,那么该对象不是“新的”。

有没有干净的方法来实现这一目标?

jpa spring-data spring-data-jpa immutability insert-update
1个回答
0
投票

例如,您可以使用Repository event handler来限制更新和删除操作:

@RepositoryEventHandler(MyEntity.class)
public class MyEntityEventHandler {

  @HandleBeforeSave
  public void handleUpdate(MyEntity entity) {
      throw new HttpRequestMethodNotSupportedException("Update")
  }

  @HandleBeforeDelete
  public void handleDelete(MyEntity entity) {
      throw new HttpRequestMethodNotSupportedException("Delete")
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.