Domanda

I'm using an environment with guice-servlet running on a tomcat and hibernate under guice-persist. The problem I've encountered is that when I use em.getReference() in one request the loaded proxy object stays in the entitymanager cache and may appear in another request where I expect to have an object completely loaded from the DB.

I used to using hibernate in EJB3 environment where it is a default behavior. The entity manager cache is clear for each new request. Isn't it a more safe behavior for guice-persist to clear the session for each request? Or at least to give it as a setting for JpaPersistModule?

There is a special flag in hibernate SessionImpl "autoClear" which is responsible for EJB3 behavior. Is there any way I could enable the flag when the new entity manager is being created by JpaPersistModule?

È stato utile?

Soluzione

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

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

Inside an interceptor I'm getting SessionImpl through EntityManagerImpl and setting 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;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top