如何覆盖 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
EntityManager
caches. Thus a subsequentfindOne(…)
might/will still return the old instance of the object you tried to delete in case theEntityManager
had already loaded it. To prevent that, set theclearAutomatically
flag in@Modifying
totrue
but 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
@PreUpdate
event will not get notified. Also any cascade operations
相关文章