Java tutorial
/* * Copyright 2010-2012 the original author or authors. * * 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 org.reusables.jpa; import static org.springframework.orm.jpa.EntityManagerFactoryUtils.getTransactionalEntityManager; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import org.hibernate.ejb.HibernateEntityManager; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.annotation.Required; import org.springframework.orm.jpa.EntityManagerFactoryUtils; /** * {@link FactoryBean} for accessing the {@link EntityManager} of the current transaction. * * <p>Factory that creates a proxy for the {@link HibernateEntityManager} interface. * The proxy reroutes calls to the {@link EntityManager} returned by {@link EntityManagerFactoryUtils#getTransactionalEntityManager(EntityManagerFactory)}. * </p> * * @author marcel */ public class HibernateEntityManagerFactoryBean implements FactoryBean<HibernateEntityManager>, InvocationHandler { private EntityManagerFactory entityManagerFactory; @Required public void setEntityManagerFactory(final EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } @Override public Class<?> getObjectType() { return HibernateEntityManager.class; } @Override public boolean isSingleton() { return true; } @Override public HibernateEntityManager getObject() throws Exception { return (HibernateEntityManager) Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] { HibernateEntityManager.class }, this); } @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { return method.invoke(getTransactionalEntityManager(this.entityManagerFactory), args); } }