Spring Data Repository @Query - Update and return modified entity

前端 未结 3 386
旧时难觅i
旧时难觅i 2020-12-09 19:52

let\'s assume we have a Spring Data repository interface with a custom method...

@Modifying
@Transactional
@Query(\"UPDATE MyEntity SET deletedAt = CURRENT_T         


        
相关标签:
3条回答
  • 2020-12-09 20:34
    @Modifying(clearAutomatically=true)
    

    Its works for me.

    0 讨论(0)
  • 2020-12-09 20:40

    There are two ways to do that:

    The JPA idiomatic way to do this is to load the entities first, then changing them using Java code.

    Doing this in a transaction will flush the changes to the database.

    If you insist on doing a batch update you need to mark the entities as part of the update. Maybe with a timestamp, maybe the update itself already marks them. And then you reload them using a select statement that uses the marker set during the update.

    Note that you have to ensure that the entities don't exist yet in your EntityManager, otherwise you will keep the old state there. This is the purpose of @Mdoifying(clearAutomatically=true) recommended by other answers.

    0 讨论(0)
  • 2020-12-09 20:49

    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

    0 讨论(0)
提交回复
热议问题