If you get the updated TBL after updating the DB in a single thread, you can get the status. Even if you get the updated TBL after the DB is updated in another place (separate thread or hitting the DB directly), you cannot get the latest information.
For example, in the following example ...
1.Create record with saveAndFlush in a thread/update
2.Loop DB acquisition process for status monitoring in the same thread
3.Another thread/Update the corresponding record with another service etc.
4.If a DB change is detected in the loop, some processing is performed. ★ Even if you perform a DB search here, you cannot get the latest updated DB data.
When saveAndFlush is performed, the Entity is registered in the persistence context of EntityManager, and that Entity is cached until the thread ends according to the JPA standard specifications. Even if the DB is updated externally, EntityManager does not detect it. In other words, even if you search with the cache remaining, you can only get the DB value in the cached state.
If you clear or detach the Entity cache directly and then perform a DB search, you can get the DB data after committing. (It seems that you can set it so that it does not have cache from the beginning, but it may be less necessary to disable the standard specification) It is necessary to execute the following processing before searching with repository etc.
//DI EntityManager
@PersistenceContext
EntityManager entityManager;
public void clearEntityCache() {
//Detach to clear the cache as a common process()Not clear()use.
entityManager.clear();
}
reference:
Recommended Posts