package org.amc.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;

import org.apache.log4j.Logger;

/**
 * Fetches and holds a reference to the Persistence EntityManager
 * @author adrian
 *
 */
public abstract class DAO
{
	private static Logger logger=Logger.getLogger(DAO.class);
	private EntityManagerFactory emf;
	private EntityManager em;
	
	private final String PERSISTENCE_UNIT_NAME="myDatabase";
	
	public DAO()
	{
		emf=Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
		em=emf.createEntityManager();
	}
	
	@PersistenceUnit(name = PERSISTENCE_UNIT_NAME)
	public void setEm(EntityManager em)
	{
		logger.info("EntityManager set to "+em.toString());
		this.em = em;
	}
	
	/**
	 * 
	 * @return EntityManager for subclass to use
	 */
	protected EntityManager getEntityManager()
	{
		return em;
	}
}

@@ -922,17 +922,319 @@
 %7B%0A%09%09
-return em
+//Reopen the EntityManager if closed%0A%09%09if(em!=null && !em.isOpen())%0A%09%09%7B%0A%09%09%09em=emf.createEntityManager();%0A%09%09%7D%0A%09%09return em;%0A%09%7D%0A%09%0A%09@Override%0A%09public void finalize()%0A%09%7B%0A%09%09//close EntityManager%0A%09%09if(em!=null && em.isOpen())%0A%09%09%09em.close();%0A%09%09//close EntityManagerFactory%0A%09%09if(emf!=null && emf.isOpen())%0A%09%09%09emf.close()
 ;%0A%09%7D

Add handling for a closed entitymanager