View Javadoc
1   /*
2    * Copyright 2010-2024 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *    https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.mybatis.spring;
17  
18  import java.util.Properties;
19  
20  import org.apache.ibatis.executor.Executor;
21  import org.apache.ibatis.plugin.Interceptor;
22  import org.apache.ibatis.plugin.Intercepts;
23  import org.apache.ibatis.plugin.Invocation;
24  import org.apache.ibatis.plugin.Plugin;
25  import org.apache.ibatis.plugin.Signature;
26  
27  /**
28   * Keeps track of Executor commits, rollbacks and close status.
29   * <p>
30   * The Executor is not accessible from DefaultSqlSession, so it is much easier to use an Interceptor rather than
31   * subclass a new SqlSessionFactory, etc. Also, there is the potential to change the default MyBatis behavior, which
32   * could change the test results.
33   */
34  @Intercepts({ @Signature(type = Executor.class, method = "commit", args = { boolean.class }),
35      @Signature(type = Executor.class, method = "rollback", args = { boolean.class }),
36      @Signature(type = Executor.class, method = "close", args = { boolean.class }) })
37  final class ExecutorInterceptor implements Interceptor {
38  
39    private int commitCount;
40  
41    private int rollbackCount;
42  
43    private boolean closed;
44  
45    @Override
46    public Object intercept(Invocation invocation) throws Throwable {
47      if ("commit".equals(invocation.getMethod().getName())) {
48        ++this.commitCount;
49      } else if ("rollback".equals(invocation.getMethod().getName())) {
50        ++this.rollbackCount;
51      } else if ("close".equals(invocation.getMethod().getName())) {
52        this.closed = true;
53      }
54  
55      return invocation.proceed();
56    }
57  
58    @Override
59    public Object plugin(Object target) {
60      return Plugin.wrap(target, this);
61    }
62  
63    @Override
64    public void setProperties(Properties properties) {
65      // do nothing
66    }
67  
68    void reset() {
69      this.commitCount = 0;
70      this.rollbackCount = 0;
71      this.closed = false;
72    }
73  
74    int getCommitCount() {
75      return this.commitCount;
76    }
77  
78    int getRollbackCount() {
79      return this.rollbackCount;
80    }
81  
82    boolean isExecutorClosed() {
83      return this.closed;
84    }
85  
86  }