Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

java - Spring Data Repository @Query - Update and return modified entity

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);

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?

Obviously...

@Modifying
@Transactional
@Query("UPDATE MyEntity SET deletedAt = CURRENT_TIMESTAMP WHERE id = ?1")
MyEntity markAsSoftDeleted(long id);

...does not work, since...

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"...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

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)

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.

Reference : Spring data jpa custom repository implemenation


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...