Database – when using JPA, avoid stale data from DB?

The problem I encountered is similar to that described in the invaliding JPA entitymanager session:

Problem: getting stale data

We run jpql queries on the SQL database, which is also changed by different applications at the same time We are using JSF spring eclipse link. Com running under Tomcat

The class that executes the jpql query is a singleton spring bean and uses the injected entitymanager:

@Component
public class DataRepository{
    @PersistenceContext
    private EntityManager entityManager;
    public List<MyDTO> getStuff(long id) {
        String jpqlQuery ="SELECT new MyDTO([...])";
        TypedQuery<MyDTO> query = entityManager.createQuery(jpqlQuery,MyDTO.class);
        return query.getResultList();
    }
[...]

(code paraphrase)

The problem is that this code does not make changes directly on the database These changes become visible only when the Tomcat instance is restarted

What did we try

We assume that this behavior is caused by the first level cache associated with the entitymanager, as described in the link problem We found two solutions

> call entityManager. before calling createQuery. Clear () (recommended in linked questions) > inject an entitymanagerfactor (using @ persistenceunit), and then create and close a new entitymanager for each query

Both solutions meet our needs – we get new numbers

Question:

>Are these two solutions correct? Which is better? > In particular, we can safely call entitymanager on the injected entitymanager Will clear () affect other code (in the same or different classes) of entitymanager that also uses injection in some way? > Is there a better way? Can we declare in some way that we want to refresh the cache, or that we want a new entitymanager?

I think this must be a fairly common problem (because it occurs when multiple applications share a database), so I think there must be a simple solution

Solution

>Creating a new entitymanager is correct and the other is not (see below)

Therefore, if a thread works with additional entities and your thread clears the entity manager, it will have serious side effects. > Well, it's hard to say If the number of entities modified outside the application is small, I will directly use the data source and jdbctemplate for corresponding operations

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>