This subsection describes the notes on using the cache functionality of the entity objects.
When JPQL and native query are used in the application to update and delete the data, the cache contents are not updated. Execute operations such as the refresh operation to obtain the database contents again.
The cache data is read in the following operations; therefore, the data is not updated in the database:
By using the cache, you can reduce the database access frequency. However, on the other hand, a time lag occurs in the data due to the cache and the frequency of optimistic lock exception might increase.
A cache exists for each persistence context. Therefore, multiple EntityManagers existing in pairs with the persistence contexts are generated simultaneously, and if the entities with the same primary keys are operated at the same time, even if the data is updated, the user might not be able to reference the updated data in a timely manner. Due to this, the optimistic lock exception occurs easily.
The following points describe the mechanism and action for the occurrence of the optimistic lock exception.
This section describes an example of cache for each persistence context in the environment shown in the following figure.
Figure 6-19 Environment described in this example
In the figure, the cache and the database are consistent and data A is already stored in the cache.
Figure 6-20 Changes in data in persistence context 1
Figure 6-21 Changes in data in persistence context 2
In such an environment, if you use the cache, the non-updated cache is left behind and an exception might occur due to the optimistic lock.
When an optimistic lock exception occurs, the relevant objects in the cache are deleted. Therefore, execute the find method or the refresh method to obtain all the related data from the database once again. With this, you can synchronize the cache data and the database.