2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.support.persistence;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
23 import javax.persistence.EntityManager;
25 import org.wamblee.support.ThreadSpecificProxyFactory;
26 import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
29 * This utility makes sure that each invocation on a certain interface is
30 * carried out within a JPA unit of work.
32 * Use {@link #getTransactionScopedEntityManager()} to get the transaction
33 * scoped entity manager to pass to services.
36 * Type of interface to proxy.
38 * @author Erik Brakkee
40 public class TransactionProxyFactory<T> {
42 private class UnitOfWorkInvocationHandler<T> implements InvocationHandler {
46 public UnitOfWorkInvocationHandler(T aService) {
51 public Object invoke(Object aProxy, final Method aMethod,
52 final Object[] aArgs) throws Throwable {
53 return TransactionProxyFactory.this.jpaBuilder
54 .execute(new JpaUnitOfWork<Object>() {
56 public Object execute(EntityManager aEm) throws Exception {
58 ENTITY_MANAGER.set(aEm);
59 return aMethod.invoke(service, aArgs);
60 } catch (InvocationTargetException e) {
61 Throwable cause = e.getCause();
62 if (cause instanceof Exception) {
63 throw (Exception) cause;
64 } else if (cause instanceof Error) {
68 throw new RuntimeException(e);
70 ENTITY_MANAGER.set(null);
78 private static final ThreadSpecificProxyFactory<EntityManager> ENTITY_MANAGER = new ThreadSpecificProxyFactory<EntityManager>(
81 private JpaBuilder jpaBuilder;
82 private Class<T> clazz;
85 * Constructs the transaction proxy.
89 public TransactionProxyFactory(JpaBuilder aJpaBuilder, Class<T> aClass) {
90 jpaBuilder = aJpaBuilder;
94 public EntityManager getTransactionScopedEntityManager() {
95 return ENTITY_MANAGER.getProxy();
98 public T getProxy(T aService) {
99 InvocationHandler handler = new UnitOfWorkInvocationHandler<T>(aService);
100 Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(),
101 new Class[] { clazz });
104 proxy = (T) proxyClass.getConstructor(
105 new Class[] { InvocationHandler.class }).newInstance(
106 new Object[] { handler });
108 } catch (Exception e) {
109 throw new RuntimeException("Could not create proxy for " +