1 16 package com.ibatis.dao.engine.impl; 17 18 import com.ibatis.common.beans.ClassInfo; 19 import com.ibatis.dao.client.Dao; 20 21 import java.lang.reflect.InvocationHandler ; 22 import java.lang.reflect.Method ; 23 import java.lang.reflect.Proxy ; 24 import java.util.HashSet ; 25 import java.util.Set ; 26 27 public class DaoProxy implements InvocationHandler { 28 29 private static final Set PASSTHROUGH_METHODS = new HashSet (); 30 31 private DaoImpl daoImpl; 32 33 static { 34 PASSTHROUGH_METHODS.add("equals"); 35 PASSTHROUGH_METHODS.add("getClass"); 36 PASSTHROUGH_METHODS.add("hashCode"); 37 PASSTHROUGH_METHODS.add("notify"); 38 PASSTHROUGH_METHODS.add("notifyAll"); 39 PASSTHROUGH_METHODS.add("toString"); 40 PASSTHROUGH_METHODS.add("wait"); 41 } 42 43 public DaoProxy(DaoImpl daoImpl) { 44 this.daoImpl = daoImpl; 45 } 46 47 public Object invoke(Object proxy, Method method, Object [] args) 48 throws Throwable { 49 Object result = null; 50 if (PASSTHROUGH_METHODS.contains(method.getName())) { 51 try { 52 result = method.invoke(daoImpl.getDaoInstance(), args); 53 } catch (Throwable t) { 54 throw ClassInfo.unwrapThrowable(t); 55 } 56 } else { 57 StandardDaoManager daoManager = daoImpl.getDaoManager(); 58 DaoContext context = daoImpl.getDaoContext(); 59 60 if (daoManager.isExplicitTransaction()) { 61 try { 63 context.startTransaction(); 64 result = method.invoke(daoImpl.getDaoInstance(), args); 65 } catch (Throwable t) { 66 throw ClassInfo.unwrapThrowable(t); 67 } 68 } else { 69 try { 71 context.startTransaction(); 72 result = method.invoke(daoImpl.getDaoInstance(), args); 73 context.commitTransaction(); 74 } catch (Throwable t) { 75 throw ClassInfo.unwrapThrowable(t); 76 } finally { 77 context.endTransaction(); 78 } 79 } 80 81 } 82 return result; 83 } 84 85 public static Dao newInstance(DaoImpl daoImpl) { 86 return (Dao) Proxy.newProxyInstance(daoImpl.getDaoInterface().getClassLoader(), 87 new Class []{Dao.class, daoImpl.getDaoInterface()}, 88 new DaoProxy(daoImpl)); 89 } 90 91 } 92 | Popular Tags |