直接从 querydsl 更新数据时如何刷新 Spring JPA?
How to refresh Spring JPA when data is updated from querydsl directly?
我正在使用 spring 数据 jpa 和 querydsl。我不想直接通过 JPA 更新,因为我必须提交一个完整的实体,这会引入不必要的查询。所以,我改用 querydsl:
val qRecord = QCoupon.coupon
jpaQueryFactory.update(qRecord)
.set(qRecord.useState, Coupon.STATE_ORDERED)
.set(qRecord.useTime, useTime)
.where(qRecord.id.eq(recordId))
.execute()
但是在同一个事务中之后的查询却获取不到最新的数据,我觉得是一级缓存的问题。
添加@Modifying
不起作用,因为我没有使用@Query
,第一个注释将被忽略。
我知道 EntityManager.clear()
可以解决这个问题。但它看起来太重了,我不确定这是个好主意。
This post explained the cause of the problem very well but not my case -- I have rejected both two answers.
@Modifying
is ignored.
EntityManager.clear()
looks too heavy, and find()
also need an entity.
感谢@Jan-WillemGmeligMeyling 的想法。因为他没有回复我,所以我写在我的回答里了。
Have you tried refreshing the entity?
entityManager.refresh(entityManager.find(Coupon.class, recordId))
em.find()
不会查找整个table,这就是我想要的。
我正在使用 spring 数据 jpa 和 querydsl。我不想直接通过 JPA 更新,因为我必须提交一个完整的实体,这会引入不必要的查询。所以,我改用 querydsl:
val qRecord = QCoupon.coupon
jpaQueryFactory.update(qRecord)
.set(qRecord.useState, Coupon.STATE_ORDERED)
.set(qRecord.useTime, useTime)
.where(qRecord.id.eq(recordId))
.execute()
但是在同一个事务中之后的查询却获取不到最新的数据,我觉得是一级缓存的问题。
添加@Modifying
不起作用,因为我没有使用@Query
,第一个注释将被忽略。
我知道 EntityManager.clear()
可以解决这个问题。但它看起来太重了,我不确定这是个好主意。
This post explained the cause of the problem very well but not my case -- I have rejected both two answers.
@Modifying
is ignored.EntityManager.clear()
looks too heavy, andfind()
also need an entity.
感谢@Jan-WillemGmeligMeyling 的想法。因为他没有回复我,所以我写在我的回答里了。
Have you tried refreshing the entity?
entityManager.refresh(entityManager.find(Coupon.class, recordId))
em.find()
不会查找整个table,这就是我想要的。