daily pastebin goal
10%
SHARE
TWEET

Untitled

a guest Aug 18th, 2018 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package proxy;
  2. import java.lang.reflect.InvocationHandler;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.Proxy;
  5. import javax.persistence.EntityManager;
  6. import javax.persistence.EntityManagerFactory;
  7. import javax.persistence.EntityTransaction;
  8. import javax.persistence.Persistence;
  9.  
  10. public class TransactionIntercepter  implements InvocationHandler {
  11.        Object target;
  12.        private TransactionIntercepter(Object target) {
  13.           this.target = target;
  14.        }
  15.        @SuppressWarnings({ "rawtypes", "unchecked" })
  16.        public static <T> T getProxyInstance(T instance) {
  17.            Class<? extends Object> clazz = instance.getClass();
  18.          // 対象クラスが実装するインターフェースのリスト
  19.            Class[] classes = clazz.getInterfaces();
  20.            TransactionIntercepter intercepter = new TransactionIntercepter(instance);
  21.            T proxyInstance = (T) Proxy.newProxyInstance(clazz.getClassLoader(), classes, intercepter);
  22.            return proxyInstance;
  23.        }
  24.        @Override
  25.        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  26.            EntityManagerFactory factory = Persistence.createEntityManagerFactory("myUnitInPersistenceXML");
  27.            EntityManager em = factory.createEntityManager();       
  28.            EntityTransaction entityTransaction = em.getTransaction();
  29.            entityTransaction.begin();
  30.            Object result=null;
  31.            try {
  32.               //EntityManaterのインスタンスをセットする
  33.               target.getClass().getDeclaredMethod("setEm",EntityManager.class).invoke(target,em);
  34.              // 実際のコードを呼び出し
  35.               result = method.invoke(this.target, args);
  36.            }catch(Exception e) {
  37.                e.printStackTrace();
  38.                entityTransaction.rollback();;
  39.                throw e;
  40.            }
  41.            entityTransaction.commit();
  42.            return result;
  43.        }
  44. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top