0

I am moving a JPA-Hibernate application from a Java EE 6 environment to a Tomcat 7 one.

The application has several DAO classes making queries on the EntityManager. In the Java EE environment I could just inject it using the @PersistenceContext annotation, and let the container manage the EntityManager. Now that I have to do it manually, I was wondering what is the way to go.

Should the entity manager be unique? If so can it be a static final field, created on startup and that every DAO class uses? Does it have a lifecycle that involves closing it and then re-opening it?

3
  • What do you mean, moving from Java EE 6 to Tomcat 7? Can you be more specific? Commented Jan 16, 2013 at 9:34
  • The application was running on glassfish, which is a JEE container, thus providing @PersistenceContext injection. Now the application will run on tomcat, which does not provide this mechanism. Commented Jan 16, 2013 at 9:53
  • If you for some reason or the other want to move away from GlassFish, why now move to TomEE? That's Tomcat as well, but with support for @PersistenceContext. Commented Jan 20, 2013 at 10:13

1 Answer 1

2

Unfortunately, you'll have to do it manually. The way I usually do it is to define a special class:

public class EMF {
  private static EntityManagerFactory factory = Persistence.createEntityManagerFactory("name");

  public static EntityManager getEntityManager() {
    return factory.createEntityManager();
  }
}

So, every time you need EntityManager, you have to create it manually. You need to handle transactions as well:

EntityManager em = EMF.getEntityManager();
EntityTransaction et = em.getTransaction();
try {
  MyEntity my = new MyEntity();
  et.begin();
  try {
    em.persist(my);
    et.commit();
  } catch (Exception ex) { 
    if (et.isActive())
      et.rollback();
  }
} finally {
  em.close();
}
Sign up to request clarification or add additional context in comments.

1 Comment

So I need to create a new EntityManager everytime I access the database. Is that correct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.