How to override a delete method on a Spring Data CrudRepository?(如何覆盖 Spring Data CrudRepository 上的删除方法?)
问题描述
我有一些无法删除的对象,必须更新一个名为已删除"的公共字段来代替它.我阅读了 那里使用 #{#entityName} 编写通用查询.出于这个原因,我尝试像这样覆盖 CrudRepository#delete(…) 方法:
I have some objects I cannot delete, and must update a common field named 'deleted' instead of it. I read there that I can write generic querys, using #{#entityName}.
For that reason I tried to override CrudRepository#delete(…) method like this:
public interface DeleteableRepository<T, ID extends Serializable> extends CrudRepository<T,ID>{
@Override
@Query("UPDATE #{#entityName} x set x.deleted = 1 where x.id = ?1")
public void delete(ID id);
}
但是我有一个单元测试显示我错了!
But the I have a unit test that shows me wrong!
@Test
public void testDelete() {
SomeDeleteableObject sdo = new SomeDeletableObject();
sdo = getDeleteableRepository().create(sdo);
Assert.assertNotNull(sdo);
Assert.assertNotNull(sdo.getId());
Assert.assertFalse(sdo.isDeleted());
getDeleteableRepository().delete(sdo);
sdo = getDeleteableRepository().findOne(sdo.getId());
//Fails here
}
难道不能像这样覆盖 CrudRepository 方法吗?
Isn't it possible to override CrudRepository methods like that?
推荐答案
要修改查询,您需要在方法中添加 @Modifying.
For modifying queries you need to add an @Modifying to the method.
确保您了解所选方法的副作用:
Be sure you are aware of the side effects of the approach you chose:
- 执行操纵查询几乎绕过了所有
EntityManager缓存.因此,后续的findOne(…)可能/仍会返回您尝试删除的对象的旧实例,以防EntityManager已经加载它.为防止这种情况发生,请将@Modifying中的clearAutomatically标志设置为true,但请注意,这将导致所有待处理的更改被清除.李> - 对于基于查询的数据操作,no 生命周期回调将被触发,no 级联将在持久化上下文级别触发.这意味着,侦听
@PreUpdate事件的实体侦听器将不会收到通知.还有任何级联操作
- Executing a manipulating query is pretty much bypassing all
EntityManagercaches. Thus a subsequentfindOne(…)might/will still return the old instance of the object you tried to delete in case theEntityManagerhad already loaded it. To prevent that, set theclearAutomaticallyflag in@Modifyingtotruebut be aware that this will cause all pending changes being wiped out. - For query based data manipulation no lifecycle callbacks will be triggered and no cascades will be triggered on the level of the persistence context. This means, entity listeners listening to an
@PreUpdateevent will not get notified. Also any cascade operations
这篇关于如何覆盖 Spring Data CrudRepository 上的删除方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何覆盖 Spring Data CrudRepository 上的删除方法?
- Jersey REST 客户端:发布多部分数据 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
