EntityManager refresh

前端 未结 6 815
生来不讨喜
生来不讨喜 2020-12-08 10:05

I have web application using JPA. This entity manager keeps bunch of entites and suddenly I update the database from other side. I use MySQL and I use

相关标签:
6条回答
  • 2020-12-08 10:43

    cache.evictAll is not working for me. So to retrieve data pushed from another app, I peform :

    em.getTransaction().begin();
    em.getTransaction().commit();
    

    After that, my find query retrieves refreshed data. I don't know if it's very safe solution but it works properly.

    0 讨论(0)
  • 2020-12-08 10:46

    If you are using EclipseLink instead of Hibernate the hint is:

    em.createNamedQuery("SomeEntity.SomeNamedQuery")
    .setHint(QueryHints.REFRESH, true)
    .getResultList();
    
    0 讨论(0)
  • 2020-12-08 11:01
    entityManager.getEntityManagerFactory().getCache().evictAll()
    

    Refresh is something different since it modifies your object. This line will just empty the cache, so if you fetch objects changed outside the entity manager, it will do an actual database query instead of using the outdated cached value.

    0 讨论(0)
  • 2020-12-08 11:03

    When you read an object into an EntityManager, it becomes part of the persistence context, and the same object will remain in the EntityManager until you either clear() it and get a new EntityManager. So if you update the database, the EntityManager will not see the change unless you call refresh() on the object, or clear() the EntityManager. This has nothing to do with the shared cache (L2) or the persistence context (L1). If you also also using a shared cache, and updating the database directly, then your shared cache will be out of date. You need to refresh() the object, or mark it as invalid to be refreshed the next time it is queried.

    Code must follow the way like. DETACH REFRESH MERGE FLUSH

    0 讨论(0)
  • 2020-12-08 11:04

    I had a similar issue and the evictAll() line above worked for me.

    Alternatively, the @Cache annotation on the entity class worked too, with the benefit of being able to control caching parameters:

    @Cache(coordinationType=CacheCoordinationType.INVALIDATE_CHANGED_OBJECTS)
    

    See: http://wiki.eclipse.org/EclipseLink/Examples/JPA/Caching

    0 讨论(0)
  • 2020-12-08 11:06

    Well, for some people (like me) that tried to add factory.getCache().evictAll(); and doesn't work, and are used JPA + Hibernate, to refresh a query add the hint org.hibernate.cacheMode to IGNORE. Example:

    em.createNamedQuery("SomeEntity.SomeNamedQuery")
      .setHint("org.hibernate.cacheMode", "IGNORE")
      .getResultList();
    
    0 讨论(0)
提交回复
热议问题