如何覆盖Spring Data CrudRepository上的delete方法? [英] How to override a delete method on a Spring Data CrudRepository?

查看:1002
本文介绍了如何覆盖Spring Data CrudRepository上的delete方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些我无法删除的对象,必须更新名为'deleted'的公共字段而不是它。我读了那里我可以使用#{#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 事件的实体侦听器将不会收到通知。任何级联操作

  • Executing a manipulating query is pretty much bypassing all 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.
  • 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

这篇关于如何覆盖Spring Data CrudRepository上的delete方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆