Spring Data Repository @Query - Update and return modified entity(Spring Data Repository @Query - 更新并返回修改后的实体)
问题描述
假设我们有一个带有自定义方法的 Spring Data 存储库接口...
let's assume we have a Spring Data repository interface with a custom method...
@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
void markAsSoftDeleted(long id);
这个方法只是简单的设置实体的deletedAt字段,ok.有什么方法可以让这个方法返回 MyEntity 的更新版本?
This method simply sets the deletedAt field of the entity, ok. Is there any way to allow this method to return an updated version of the MyEntity?
显然……
@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
MyEntity markAsSoftDeleted(long id);
...不起作用,因为...
...does not work, since...
java.lang.IllegalArgumentException:修改查询只能使用void或int/Integer作为返回类型!
java.lang.IllegalArgumentException: Modifying queries can only use void or int/Integer as return type!
是否有人知道另一种方法可以轻松实现这一点,当然除了明显的在存储库和调用者之间为此类事情添加服务层"...
Does anyon know another way to easily allow that, except of course the obvious "add a service layer between repository and caller for such things"...
推荐答案
在@Modifying annotation 上设置 clearAutomatically 属性.这将清除 EntityManager 中所有未刷新的值.
Set clearAutomatically attribute on @Modifying annotation.That will clear all the non-flushed values from EntityManager.
@Modifying(clearAutomatically=true)
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
MyEntity markAsSoftDeleted(long id);
要在提交更新之前刷新您的更改,最新的 spring-data-jpa 在 @ModifyingAttribute 上有另一个属性.但我认为它仍在 2.1.M1 版本中.
To flush your changes before committing the update latest spring-data-jpa has another attribute on @ModifyingAttribute. But I think its still in 2.1.M1 release.
@Modifying(clearAutomatically=true, flushAutomatically = true)
请查看对应的jira bug request:https://jira.spring.io/browse/DATAJPA-806
Please check corresponding jira bug request: https://jira.spring.io/browse/DATAJPA-806
另一种方法是您可以实现自定义存储库实现并在完成查询执行后返回您更新的实体.
Another approach can be you can implement custom repostiory Implementation and return your updated entity after done with the query execution.
参考:Spring 数据 jpa自定义存储库实现
这篇关于Spring Data Repository @Query - 更新并返回修改后的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring Data Repository @Query - 更新并返回修改后的实体
基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
