1 package de.example.mybatis.interceptor;
3 import java.lang.reflect.Field;
4 import java.lang.reflect.Method;
5 import java.util.Properties;
7 import org.apache.ibatis.executor.CachingExecutor;
8 import org.apache.ibatis.executor.Executor;
9 import org.apache.ibatis.plugin.Interceptor;
10 import org.apache.ibatis.plugin.Invocation;
11 import org.apache.ibatis.session.Configuration;
12 import org.apache.ibatis.transaction.Transaction;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
16 import de.example.mybatis.executor.ReuseBatchExecutor;
19 * Too much hacking for doing this stuff. No other way of using my own Executor when using Spring Mybatis.
22 public class ReuseBatchExecutorInterceptor implements Interceptor {
23 private static final Logger LOGGER = LoggerFactory.getLogger(ReuseBatchExecutorInterceptor.class);
26 public Object intercept(Invocation invocation) throws Throwable {
27 Method method = invocation.getMethod();
28 Object[] args = invocation.getArgs();
29 Object target = invocation.getTarget();
31 return invocation.proceed();
35 public Object plugin(Object target) {
36 Object result = target;
38 if (target instanceof CachingExecutor) {
39 CachingExecutor cachingExecutor = (CachingExecutor) target;
41 Field delegateField = getField(cachingExecutor.getClass(), "delegate");
42 delegateField.setAccessible(true);
43 Object delegatedExecutor = delegateField.get(cachingExecutor);
44 Executor executor = doReuseBatchExecutor((Executor) delegatedExecutor);
45 result = new CachingExecutor(executor);
46 } catch (IllegalAccessException e) {
47 LOGGER.error("Error: ", e);
48 } catch (NoSuchFieldException e) {
49 LOGGER.error("Error: ", e);
51 } else if (target instanceof Executor){
52 result = doReuseBatchExecutor((Executor) target);
59 public void setProperties(Properties properties) {
63 private static Field getField(Class clazz, String fieldName) throws NoSuchFieldException {
65 return clazz.getDeclaredField(fieldName);
66 } catch (NoSuchFieldException e) {
67 Class superClass = clazz.getSuperclass();
68 if (superClass == null) {
71 return getField(superClass, fieldName);
76 private ReuseBatchExecutor doReuseBatchExecutor(Executor executor) {
77 Configuration configuration = null;
79 final Field configurationField = getField(executor.getClass(), "configuration");
80 configurationField.setAccessible(true);
81 configuration = (Configuration) configurationField.get(executor);
82 } catch (IllegalAccessException e) {
83 LOGGER.error("Error: ", e);
84 } catch (NoSuchFieldException e) {
85 LOGGER.error("Error: ", e);
88 final Transaction trx = executor.getTransaction();
89 return new ReuseBatchExecutor(configuration, trx);