JAVA: an EntityManager object in a multithread environment

后端 未结 5 1119
傲寒
傲寒 2020-12-07 16:50

if I have multiple threads, each use injector to get the EntityManager object, each use the em object to select a list of other class objects. Ready to be used in a for loop

5条回答
  •  醉梦人生
    2020-12-07 17:30

    Here is full working thread-safe Entity Manager Helper.

    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    
    public class EntityManagerHelper {
    
        private static final EntityManagerFactory emf;
        private static final ThreadLocal threadLocal;
    
        static {
            emf = Persistence.createEntityManagerFactory("Persistent_Name");
            threadLocal = new ThreadLocal();
        }
    
        public static EntityManager getEntityManager() {
            EntityManager em = threadLocal.get();
    
            if (em == null) {
                em = emf.createEntityManager();
                // set your flush mode here
                threadLocal.set(em);
            }
            return em;
        }
    
        public static void closeEntityManager() {
            EntityManager em = threadLocal.get();
            if (em != null) {
                em.close();
                threadLocal.set(null);
            }
        }
    
        public static void closeEntityManagerFactory() {
            emf.close();
        }
    
        public static void beginTransaction() {
            getEntityManager().getTransaction().begin();
        }
    
        public static void rollback() {
            getEntityManager().getTransaction().rollback();
        }
    
        public static void commit() {
            getEntityManager().getTransaction().commit();
        }
    }
    

提交回复
热议问题