Spring JPA禁用合并

huangapple go评论74阅读模式
英文:

Spring jpa disable merge

问题

I want disable merge in jpa repository. It should only be possible to create new records and prohibit updating old ones. <br>
So, how to disable the update of records for the repository if I extend from JpaRepository?

英文:

i want disable merge in jpa repository. It should only be possible to create new records and prohibit updating old ones. <br>
So, how to disable the update of records for the repository if i extends from JpaRepository?

答案1

得分: 1

  • 使您的实体成为不可变的可以阻止对托管实体的更改,因此在事务中不会传播任何更改。

  • 但是,它不会阻止Hibernate更新数据库记录,如果您传递了具有分配的ID并且它已经存在于数据库中的不可变记录。

  • 因此,我认为您可以查看@PreUpdate实体监听器并抛出异常。因此,如果有人尝试更新,它将抛出异常,更新将不会发生。

  • 但最好的方法是创建一个服务,该服务隐藏了存储库,并且
      - 服务在save之前执行find以避免第二点
      - 使实体不可变以确保第一点。

英文:
  • Making your entity immutable can stop changes happening to managed entities and as a result no changes will be propagated within the transaction.

  • However it does not stop hibernate updating the database record, if you passed immutable record with id assigned and it already exists in db.

  • So I think you can look into @PreUpdate entity listener and throw exception. So if someone tries to update, it will throw exception and update will not happen.

  • But the best way is to create service which hides the repository and

  • Service does a find before save to avoid second point

  • Make the entity immutable to make sure first point.

答案2

得分: 0

你需要的基本上是一个不可变实体,从你的实体中移除设置器,使用构建器来创建新的实体。

英文:

What you need is basically an immutable entity, remove setters from your entity and use builders to create new entities.

huangapple
  • 本文由 发表于 2020年8月3日 23:38:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/63232528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定