Spring Data Repository @Query - 更新并返回修改后的实体

2022-01-18 00:00:00 spring java spring-data

假设我们有一个带有自定义方法的 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自定义存储库实现

相关文章