Spring Data Repository @Query-更新并返回修改后的实体 [英] Spring Data Repository @Query - Update and return modified entity

查看:213
本文介绍了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);

此方法只是将实体的deleteAt字段设置为确定.有什么方法可以让此方法返回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注释上设置 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错误请求: 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.

参考资料:春季数据jpa自定义存储库实现

这篇关于Spring Data Repository @Query-更新并返回修改后的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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