Java tutorial
/* * Copyright 2013 Marcelo Morales me@marcelomorales.name * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package name.marcelomorales.siqisiqi.openjpa.guice; import com.google.common.base.Preconditions; import javax.inject.Inject; import javax.inject.Provider; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * @author Marcelo Morales * Since: 9/17/13 */ public class EntityManagerProvider implements Provider<EntityManager>, UnitOfWork { private final ThreadLocal<EntityManager> entityManager = new ThreadLocal<>(); private final EntityManagerFactory emFactory; @Inject public EntityManagerProvider(EntityManagerFactory emFactory) { this.emFactory = emFactory; } public EntityManager get() { if (!isWorking()) { begin(); } EntityManager em = entityManager.get(); Preconditions.checkState(null != em, "Requested EntityManager outside work unit."); return em; } public void begin() { Preconditions.checkState(null == entityManager.get(), "Work already begun on this thread. Looks like you have called UnitOfWork.begin() twice" + " without a balancing call to end() in between."); entityManager.set(emFactory.createEntityManager()); } public void end() { EntityManager em = entityManager.get(); // Let's not penalize users for calling end() multiple times. if (null == em) { return; } em.close(); entityManager.remove(); } public boolean isWorking() { return entityManager.get() != null; } }