n);
}
/**
* Mapper Proxy
* executing mapper method and close sqlsession
* @author boyce
* @version 2014-4-9
*/
private static class MapperProxy implements InvocationHandler {
private Mapper mapper;
private SqlSession sqlSession;
private MapperProxy(Mapper mapper, SqlSession sqlSession) {
this.mapper = mapper;
this.sqlSession = sqlSession;
}
private static Mapper bind(Mapper mapper, SqlSession sqlSession) {
return (Mapper) Proxy.newProxyInstance(mapper.getClass().getClassLoader(),
mapper.getClass().getInterfaces(), new MapperProxy(mapper, sqlSession));
}
/**
* execute mapper method and finally close sqlSession
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object object = null;
try {
object = method.invoke(mapper, args);
} catch(Exception e) {
e.printStackTrace();
} finally {
sqlSession.close();
}
return object;
}
}
}
客户端使用场景:
Java代码
UserMapper mapper = MapperFactory.HO.createMapper(UserMapper.class);
User user = mapper.getUserById(162L);
System.out.println(user);
ok,如果大家有什么更优雅的设计方案请不吝分享分享。
|