JPA UPDATE not flushing

April 3, 2020

I had a problem where an UPDATE in a Spring repository wasn't updating the cached hibernate data. The update was working on the database, but stale information was held and returned from the service.

@Modifying(flushAutomatically = true)
@Query("UPDATE RoomDayEntity rd SET rd.cacheStaffMemberName = ?5, rd.staffMember.id = ?4 WHERE ...")
public int updateResourceInRoom(Long storeId, long roomId, LocalDate diaryDate, Long resourceId, String resourceName);

After running this update, if I attempted to return the values for a RoomDayEntity by running other services, those services didn't know the UPDATE had happened and so returned stale values.

I needed to tell the UPDATE to clear the EntityManager data store, which can be done by adding clearAutomatically = true to the @Modifying annotation.

@Modifying(flushAutomatically = true, clearAutomatically = true)
@Query("UPDATE RoomDayEntity rd SET rd.cacheStaffMemberName = ?5, rd.staffMember.id = ?4 WHERE ...")
public int updateResourceInRoom(Long storeId, long roomId, LocalDate diaryDate, Long resourceId, String resourceName);