Proper Usage of Entity Manager from EntityManagerFactory

I am having some trouble understanding the proper usage of entity manager when querying for objects and or deleting/creating. Right now for any database transactions I have several service methods that open and close new entity managers like so:

public static Long getCountApplicants(String active){

    EntityManager entityManager = factory.createEntityManager();
    long value = (Long) entityManager.createQuery("select count(distinct a) from    Applicant a  where a.active = " +active).getSingleResult();
    System.out.println("get count app query");
    entityManager.close();
    return value;
}

Since I have a Java EE app with a persistence.xml file that defines my unit, why can't I declare only one from my factory and use it throughout the life of my app? Is there any performance or memory leak issues with using just one of these objects?

Update:

I am using the following stack, Spring Framework/JPA Eclipselink

Answers


Long story short: Since you're using Spring, you're better off defining the Entity Manager as an attribute of your DAO like so:

@PersistenceContext
EntityManager em;

Your code then becomes:

public static Long getCountApplicants(String active){
    long value = (Long) em.createQuery("select count(distinct a) from    Applicant a  where a.active = " +active).getSingleResult();
    System.out.println("get count app query");
    return value;
}

This will work only with Non Extended Persistence Contexts. The EntityManager injected by Spring will be threadsafe. Whether you need to configure an LocalEntityManagerFactorBean application-managed or LocalContainerEntityManagerFactoryBean container-managed Entity Manager is just a matter of configuration in the Spring configuration files.


EntityManager is generally not threadsafe when application managed.

http://docs.oracle.com/javaee/6/tutorial/doc/bnbqw.html

However, if you're using a container managed version, it should be. You would inject it:

@PersistenceContext
EntityManager entityManager;

Spring is one such container that can do this. The link above is a helpful resource.


Need Your Help

mailchimp subscription error message tweak jquery

jquery css mailchimp

hey guys so i have this mailchimp form here

VS 2010 installer project not carrying shared referenced assemblies to all outputs

c# .net visual-studio-2010 installer installation-package

I am setting up an installer project for a C# solution and I encounter a dependency problem: