View Javadoc
1   /*
2    * Copyright 2004-2022 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 com.ibatis.sqlmap.engine.transaction;
17  
18  import java.sql.Connection;
19  import java.sql.SQLException;
20  
21  /**
22   * The Class IsolationLevel.
23   */
24  public class IsolationLevel {
25  
26    /** The Constant UNSET_ISOLATION_LEVEL. */
27    public static final int UNSET_ISOLATION_LEVEL = -9999;
28  
29    /** The isolation level. */
30    private int isolationLevel = UNSET_ISOLATION_LEVEL;
31  
32    /** The original isolation level. */
33    private int originalIsolationLevel = UNSET_ISOLATION_LEVEL;
34  
35    /**
36     * Sets the isolation level.
37     *
38     * @param isolationLevel
39     *          the new isolation level
40     */
41    public void setIsolationLevel(int isolationLevel) {
42      this.isolationLevel = isolationLevel;
43    }
44  
45    /**
46     * Apply isolation level.
47     *
48     * @param conn
49     *          the conn
50     *
51     * @throws SQLException
52     *           the SQL exception
53     */
54    public void applyIsolationLevel(Connection conn) throws SQLException {
55      if (isolationLevel != UNSET_ISOLATION_LEVEL) {
56        originalIsolationLevel = conn.getTransactionIsolation();
57        if (isolationLevel != originalIsolationLevel) {
58          conn.setTransactionIsolation(isolationLevel);
59        }
60      }
61    }
62  
63    /**
64     * Restore isolation level.
65     *
66     * @param conn
67     *          the conn
68     *
69     * @throws SQLException
70     *           the SQL exception
71     */
72    public void restoreIsolationLevel(Connection conn) throws SQLException {
73      if (isolationLevel != originalIsolationLevel) {
74        conn.setTransactionIsolation(originalIsolationLevel);
75      }
76    }
77  
78  }