How to inject the JPA EntityManager in a Tomcat-based web application?

Dear hibernate community,
I am running into problems because tomcat is not a complaint java EE server, hence I need to manage entitymanager myself (application managed entitymanager). However hibernate throws an exception “org.hibernate.HibernateException: Flush during cascade is dangerous” when multiple threads works under the same tables… my question is is this the right way to manage entitymanager in a thread-safety.

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

public class EntityManagerHelper {

    private static final EntityManagerFactory emf;
    private static final ThreadLocal<EntityManager> threadLocal;

    static {
        emf = Persistence.createEntityManagerFactory("Persistent_Name");
        threadLocal = new ThreadLocal<EntityManager>();

    public static EntityManager getEntityManager() {
        EntityManager em = threadLocal.get();

        if (em == null) {
            em = emf.createEntityManager();
            // set your flush mode here
        return em;

    public static void closeEntityManager() {
        EntityManager em = threadLocal.get();
        if (em != null) {

    public static void closeEntityManagerFactory() {

    public static void beginTransaction() {

    public static void rollback() {

    public static void commit() {

thank you very much

It’s much better if you’re using a framework for that, so you have 2 choices:

  1. You can use TomEE which implements the Java EE CDI spec
  2. You can use Spring to inject the EntityManager and use declarative transaction boundaries