问题描述
我有一些无法删除的对象,必须更新一个名为已删除"的公共字段来代替它.我阅读了 那里使用 #{#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 上的删除方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)