Perhaps AOP, ThreadLocal and a DelegatingDataSource could offer a solution:
Code:
public SameConnectionDataSource extends DelegatingDataSource
{
private static ThreadLocal sameConnection = new ThreadLocal();
public static Object getSameConnection() { sameConnection.get(); }
public static void setSameConnection(Object c) { sameConnection.set(c); }
public Connection getConnection() {
Object con = sameConnection.get();
if (con == null) {
con = getTargetDataSource().getConnection();
sameConnection.set(con);
}
return con;
}
public Connection getConnection(String user, String password) {
Object con = sameConnection.get();
if (con == null) {
con = getTargetDataSource().getConnection(user, password);
sameConnection.set(con);
}
return con;
}
}
public SameConnectionInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
// Save old connection in case its invoked in a nested manner.
Object oldConnection = SameConnectionDataSource.getSameConnection();
Object rval = invocation.proceed();
SameConnectionDataSource.setSameConnection(oldConnection);
return rval;
}
}
Does this look like it would work?