Pii
Pii

Reputation: 301

Java Hibernate Memory leak

I'm developing a Flex application with BlazeDS and I'm experiencing memory leak when using java to query from MySQL in hibernate. Can anyone tell me how to deal with this memory leak? It seems that each time query is invoke java.exe takes more memory.

Thanks

Sample of my java

factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
EntityManager em = factory.createEntityManager();

Query find = em.createNamedQuery("Plan.findByStudentId");
find.setParameter("studentId", studentID);

List<Plan> c = find.getResultList();

return c;

Upvotes: 1

Views: 2557

Answers (2)

Bozho
Bozho

Reputation: 597016

I assume you are leaving your EntityManager open after you return the data to flex, which in turn means that your MySQL Connection remains open. That's where the memory leak most likely comes from. So - close your EntityManager.

In anoter comment you said that you are using GlassFish. That's a whole new scenario. Is your class this a Servlet? An EJB?. GlassFish is supposed to manage your EntityManagers (if the class itself is managed), so you don't have to create or close it yourself. In such cases use @PersistenceContext annotation to inject the EntityManager (instead of using Persistence.create..)

But the thing you must do whatever the setup, is to start a profiler and see where is this memory allocated.

Upvotes: 2

akellakarthik
akellakarthik

Reputation: 363

Hi you just need to out your code in a try catch block and close the entity manager.

try{
    if(em !=null){
        em.close();
    }
} catch(Exception e){
    e.printStackTrace();
} finally {
    em.close();
}

Upvotes: 0

Related Questions