Spring Boot Data JPA - Modifying update query - Refresh persistence context

前端 未结 2 1349
不思量自难忘°
不思量自难忘° 2020-12-07 10:59

I\'m working with Spring Boot 1.3.0.M4 and a MySQL database.

I have a problem when using modifying queries, the EntityManager contains outdated entities after the qu

2条回答
  •  一生所求
    2020-12-07 11:45

    I know this is not a direct answer to your question, since you already have built a fix and started a pull request on Github. Thank you for that!

    But I would like to explain the JPA way you can go. So you would like to change all entities which match a specific criteria and update a value on each. The normal approach is just to load all needed entities:

    @Query("SELECT * FROM Email e where e.active = true and e.expire <= NOW()")
    List findExpired();
    

    Then iterate over them and update the values:

    for (Email email : findExpired()) {
      email.setActive(false);
    }
    

    Now hibernate knows all changes and will write them to the database if the transaction is done or you call EntityManager.flush() manually. I know this won't work well if you have a big amount of data entries, since you load all entities into memory. But this is the best way, to keep the hibernate entity cache, 2nd level caches and the database in sync.

    Does this answer say "the `@Modifying´ annotation is useless"? No! If you ensure the modified entities are not in your local cache e.g. write-only application, this approach is just the way to go.

    And just for the record: you don't need @Transactional on your repository methods.

    Just for the record v2: the active column looks as it has a direct dependency to expire. So why not delete active completely and look just on expire in every query?

提交回复
热议问题