Automatically cleared sessions using guice-persist

I am using an environment with a guice servlet running on tomcat and hibernate under guice-persist. The problem I am facing is that when I use em.getReference () in one request, the loaded proxy object remains in the existing cache, and may appear in another request, where I expect the object to be fully loaded from DB

I used hibernation in an EJB3 environment where this is the default behavior. For each new request, the organizationโ€™s cache manager is understandable. Isn't this a safer behavior for guice-persist to clear the session for each request? Or at least give it as a setting for a JpaPersistModule?

Hibernate SessionImpl "autoClear" has a special flag that is responsible for the behavior of EJB3. Is there a way to enable the flag when a new entity manager is created by JpaPersistModule?

+4
source share
1 answer

Solved it this way: I created an AOP interceptor to catch the EntityManager returned by JpaPersistService.

bindInterceptor(Matchers.subclassesOf(PersistService.class), Matchers.returns(Matchers.identicalTo(EntityManager.class)), new EntityManagerInterceptor() ); 

Inside the interceptor, I get SessionImpl via EntityManagerImpl and set the autoClear property.

 public Object invoke(MethodInvocation invocation) throws Throwable { Object result = invocation.proceed(); if (result instanceof EntityManagerImpl) { EntityManagerImpl castedEm = (EntityManagerImpl) result; ((SessionImpl) castedEm.getSession()).setAutoClear(true); } return result; } 
+3
source

Source: https://habr.com/ru/post/1394822/


All Articles