我有一些无法删除的对象,必须更新一个名为已删除"的公共字段来代替它.我阅读了 那里使用 #{#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
,但请注意,这将导致所有待处理的更改被清除.李>@PreUpdate
事件的实体侦听器将不会收到通知.还有任何级联操作EntityManager
caches. Thus a subsequent findOne(…)
might/will still return the old instance of the object you tried to delete in case the EntityManager
had already loaded it. To prevent that, set the clearAutomatically
flag in @Modifying
to true
but be aware that this will cause all pending changes being wiped out.@PreUpdate
event will not get notified. Also any cascade operations这篇关于如何覆盖 Spring Data CrudRepository 上的删除方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!