我创建了两个这样的类:
//This class has the EntityManagerFactory instance that is going to be shared between the classes
public class ManageConnection {
protected static EntityManagerFactory emf = null;
private static String persitenceName="locationtracker";
//Anonymous Block that is going to be called (beofre) on every call for constructor of this class
//whether through inheritance or normal instantiation
{
if(emf==null || !emf.isOpen())
emf = Persistence.createEntityManagerFactory(persitenceName);
}
public static EntityManagerFactory getEntityManagerFactory(){
return ManageConnection.emf;
}
}
//This class actually handles the trasactional management
public class ManageTransaction extends ManageConnection{
/**
*
*/
public ManageTransaction() {
super();
this.entityManager = emf.createEntityManager();
this.transaction = this.entityManager.getTransaction();
}
/**
* @param entityManager
* @param transaction
*/
public ManageTransaction(EntityManager entityManager,EntityTransaction transaction) {
super();
this.entityManager = entityManager;
this.transaction = transaction;
}
private EntityManager entityManager;
private EntityTransaction transaction;
/**
* @return the entityManager
*/
public EntityManager getEntityManager() {
return entityManager;
}
/**
* @param entityManager the entityManager to set
*/
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
/**
* @return the transaction
*/
public EntityTransaction getTransaction() {
return transaction;
}
/**
* @param transaction the transaction to set
*/
public void setTransaction(EntityTransaction transaction) {
this.transaction = transaction;
}
public void closeEntityManager(){
if(entityManager!=null && entityManager.isOpen()){
entityManager.close();
}
}
public void close(){
this.closeEntityManager();
}
public void flush(){
entityManager.flush();
}
public void begin(){
this.transaction.begin();
}
public void commit(){
this.flush();
this.transaction.commit();
}
public void persist(Object objToPersist){
this.entityManager.persist(objToPersist);
}
}//end of ManageTransaction class
现在,如果我想使用它,我会这样使用:
.
.
.
.
.
.
ManageTransaction mt = new ManageTransaction();
方案 1
mt.getEntityManager().find(blah,blah);//works perfectly
方案 2
mt.begin();
<PersistenceObject> objName = new <PersistenceObject>();
mt.persist(objName);
mt.close();
方案 3
String jpaquery = "blah blah";
TypedQuery<ClassType> tq = mt.getEntityManager().createQuery(jpaquery,<Class>.class);
List<ClassType> all = tq.getResultList();
这样,每次不需要创建新事务时,我只需创建一个事务并在我的班级的每个地方都使用该事务,最后关闭它。
这样我共享EntityManager的问题就解决了,因此在任何情况下都不会抛出异常。
:)