0

I'm using spring data jpa and querydsl. I don't want to update directly through JPA because I have to submit a complete entity, which introduces an unnecessary query. So, I use querydsl instead:

val qRecord = QCoupon.coupon
jpaQueryFactory.update(qRecord)
    .set(qRecord.useState, Coupon.STATE_ORDERED)
    .set(qRecord.useTime, useTime)
    .where(qRecord.id.eq(recordId))
    .execute()

But the query after that in the same transcation cannot get the latest data, I think it has something to do with the first-level cache.

Adding @Modifying doesn't work because I didn't use @Query, the first annotation will be ignored.

I know EntityManager.clear() can fix that. But it looks too heavy, I'm not sure this is a good idea.

This post explained the cause of the problem very well but not my case -- I have rejected both two answers.

  1. @Modifying is ignored.
  2. EntityManager.clear() looks too heavy, and find() also need an entity.
Chenhe
  • 924
  • 8
  • 19
  • Have you tried refreshing the entity? ```entityManager.refresh(entityManager.find(Coupon.class, recordId))``` – Jan-Willem Gmelig Meyling Sep 13 '21 at 07:30
  • Does this answer your question? [Spring data - Refresh entity after "manual" backend query update](https://stackoverflow.com/questions/33825429/spring-data-refresh-entity-after-manual-backend-query-update) – Jens Schauder Sep 13 '21 at 08:40
  • @Jan-WillemGmeligMeyling Good, it works. Pls put your idea to answer area so that I can accept it. – Chenhe Sep 13 '21 at 14:30
  • @JensSchauder I have read that post and its related post. They explained the cause of the problem very well, but unfortunately, it was not suitable for my usecase. Thank you all the same. – Chenhe Sep 13 '21 at 14:32
  • The question even describes the usage of `refresh` in the question itself, which you claim solves your problem. – Jens Schauder Sep 13 '21 at 14:47
  • @JensSchauder Yes. But `refresh` also need a complete entity which I want to avoid (unnecessary query). @Jan-Willem Gmelig Meyling's suggestion give me another choice: `em.find()` will not look up the entire table. – Chenhe Sep 13 '21 at 14:52

1 Answers1

0

Thanks @Jan-WillemGmeligMeyling 's idea. Because he didn't reply to me, I wrote it in my answer.

Have you tried refreshing the entity? entityManager.refresh(entityManager.find(Coupon.class, recordId))

em.find() will not look up the entire table, that's what I want.

Chenhe
  • 924
  • 8
  • 19