Single EntityManagerFactory object across various Restlet Resources


In my short experience with EntityManagerFactory objects, I have seen that creating a new object of this type takes a considerable amount of time its actually a few seconds, so you realize you are waiting for something to happen. Now if you have a Restlet application or any web application for that matter, if you start creating a new EntityManagerFactory in every Servlet or Restlet, then the waiting time for the application to do something becomes quite significant…

So what is the workaround for this??

One way to reduce this time is to use a Singleton style class which will return an already created EMF object(if it exists) or will return a new one.

I tried this, and my application has improved very much. So here is the Singleton class that you can use –

EmfSingleton.java

import javax.persistence.Persistence;
import javax.persistence.EntityManagerFactory;
public class EmfSingleton {

protected EmfSingleton()
{

}
static private EntityManagerFactory emf=null;

static public EntityManagerFactory getEmfInstance()
{
if(null == emf)
{
emf=Persistence.createEntityManagerFactory(“<persistence-Unit-Name>”);
}
return emf;
}
}

And the usage will be –

Wherever I want a EMF object I will say

EntityManagerFactory emf = EmfSingleton.getEmfInstance();

Is this a good approach? I dont know. What do you think?

Advertisements

About vatsalad

Hi, I'm Vatsala
This entry was posted in Code Samples, hibernate, java and tagged , , , . Bookmark the permalink.

2 Responses to Single EntityManagerFactory object across various Restlet Resources

  1. Mike says:

    You should probably use one of the Java EE annotations and have the factory/manager injected into your code instead.

    See this blog for details.

Comments are closed.