英文:
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
beforesave
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论