View Javadoc
1   /*
2    *    Copyright 2009-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 org.apache.ibatis.cache;
17  
18  import java.util.HashMap;
19  import java.util.Map;
20  
21  import org.apache.ibatis.cache.decorators.TransactionalCache;
22  import org.apache.ibatis.util.MapUtil;
23  
24  /**
25   * @author Clinton Begin
26   */
27  public class TransactionalCacheManager {
28  
29    private final Map<Cache, TransactionalCache> transactionalCaches = new HashMap<>();
30  
31    public void clear(Cache cache) {
32      getTransactionalCache(cache).clear();
33    }
34  
35    public Object getObject(Cache cache, CacheKey key) {
36      return getTransactionalCache(cache).getObject(key);
37    }
38  
39    public void putObject(Cache cache, CacheKey key, Object value) {
40      getTransactionalCache(cache).putObject(key, value);
41    }
42  
43    public void commit() {
44      for (TransactionalCache txCache : transactionalCaches.values()) {
45        txCache.commit();
46      }
47    }
48  
49    public void rollback() {
50      for (TransactionalCache txCache : transactionalCaches.values()) {
51        txCache.rollback();
52      }
53    }
54  
55    private TransactionalCache getTransactionalCache(Cache cache) {
56      return MapUtil.computeIfAbsent(transactionalCaches, cache, TransactionalCache::new);
57    }
58  
59  }