Wednesday, March 16, 2011

How to close EnityManager when not injected?

I have a servlet running in an Oracle OCCAS server. Currently I map some data in a database to an entity class in my application using @Entity annotaion. I fail to inject the EntityManager (@PersistenceContext) though, and to my understanding that is because it is running in my servlet context and not as a separate Entity EJB. Creating the manager through the EntityManagerFactory works, though, so that is what I use at the moment.

Now, after a number of restarts of the application, I get an out of PermGen space error. I figure this is related to the persistence somehow. There is a call to EntityManager.close() in my finalize method, but it never shows up in the log.

Is this a Bad Way of doing things - am I "required" to have a separate Entity Bean, or how am I supposed to clean up the EntityManager?

From stackoverflow
  • I had a similar issue and solved it using ThreadLocal and a servlet filter.

    Here's a post on my blog detailing what you need to do; basically your servlet filter sets up the entity manager and then closes it after the servlet call completes; it makes the entity manager available as a thread local variable (per hibernate's recommendation). You also need to catch exceptions in the filter and do a rollback.

    BTW, finalize isn't guaranteed to be called in the way that you think. finalize should be called before the JVM exits, but outside of that, it could be a long while.

    E Dominique : Thanks! I will try that, or possibly go the EJB route. After all, there is a container there that can do the job.. I figured that after a redeployment, the old application object should be ready for the GC to clean up - and especially when PermGen is running low. Oh, well...

0 comments:

Post a Comment