Mybatis 소개 캐 시

      Mybatis     

Mybatis           ,             ,        。      SqlSession     ,     SqlSession      SQL     ,                ,          ,        1024 SQL。         SqlSession   。
 
       Mybatis   SQL     org.apache.ibatis.executor.Executor     ,    ,        ,   BaseExecutor,   CachingExecutor。              ,            ,           ,          ,      BaseExecutor    。
 
8.1         
                 , BaseExecutor query()     ,        PerpetualCache  ,PerpetualCache  HashMap    。         、 、        。
 
  public  List query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
    ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
    if (closed) {
      throw new ExecutorException("Executor was closed.");
    }
    if (queryStack == 0 && ms.isFlushCacheRequired()) {
      clearLocalCache();
    }
    List list;
    try {
      queryStack++;
      list = resultHandler == null ? (List) localCache.getObject(key) : null;
      if (list != null) {
        handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
      } else {
        list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
      }
    } finally {
      queryStack--;
    }
    if (queryStack == 0) {
      for (DeferredLoad deferredLoad : deferredLoads) {
        deferredLoad.load();
      }
      // issue #601
      deferredLoads.clear();
      if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
        // issue #482
        clearLocalCache();
      }
    }
    return list;
  }
 
               SESSION STATEMENT  ,   SESSION,             ,                 STATEMENT,         Mapper            。             ,  Mybatis      ,    localCacheScope  。
      
 
               ,        , testCache1 ,       SqlSession        SQL,       SQL。 testCache2 ,            SQL,        SqlSession,       SQL  。       Mybatis  Spring ,    Spring  Mapper   ,             Mapper               SqlSession  ,               ,            。                 SqlSession。             MapperFactoryBean   ,   SqlSessionDaoSupport   SqlSessionFactory   SqlSessionTemplate    。
   /**
    *          ,             SqlSession   。
* : Spring Mybatis, Mapper , SqlSession。 , testCache() , @Transactional 。 */ @Test public void testCache() { PersonMapper mapper = session.getMapper(PersonMapper.class); mapper.findById(5L); mapper.findById(5L); } @Test public void testCache2() { SqlSession session1 = this.sessionFactory.openSession(); SqlSession session2 = this.sessionFactory.openSession(); session1.getMapper(PersonMapper.class).findById(5L); session2.getMapper(PersonMapper.class).findById(5L); } 8.2 8.2.1 , , Mybatis cacheEnabled false。 cacheEnabled , true , Executor CachingExecutor。 Mybatis org.apache.ibatis.session.Configuration newExecutor 。 public Executor newExecutor(Transaction transaction, ExecutorType executorType) { executorType = executorType == null ? defaultExecutorType : executorType; executorType = executorType == null ? ExecutorType.SIMPLE : executorType; Executor executor; if (ExecutorType.BATCH == executorType) { executor = new BatchExecutor(this, transaction); } else if (ExecutorType.REUSE == executorType) { executor = new ReuseExecutor(this, transaction); } else { executor = new SimpleExecutor(this, transaction); } if (cacheEnabled) { executor = new CachingExecutor(executor); } executor = (Executor) interceptorChain.pluginAll(executor); return executor; } , Mapper.xml cache, CachingExecutor , cache Mapper.xml cache。 cache , useCache() true , select useCache true, , , useCache false 。 @Override public List query(MappedStatement ms, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException { Cache cache = ms.getCache(); if (cache != null) { flushCacheIfRequired(ms); if (ms.isUseCache() && resultHandler == null) { ensureNoOutParams(ms, parameterObject, boundSql); @SuppressWarnings("unchecked") List list = (List) tcm.getObject(cache, key); if (list == null) { list = delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); tcm.putObject(cache, key, list); // issue #578 and #116 } return list; } } return delegate. query(ms, parameterObject, rowBounds, resultHandler, key, boundSql); } 8.2.2cache , Mapper.xml cache 。 , cache , cache-ref 。 Mapper , Cache, 。Mapper Cache Mapper namespace , namespace Cache 。 8.2.2.1cache cache Cache , Mapper.xml , Mybatis Cache , PerpetualCache , LruCache ( )。 XMLMapperBuilder cacheElement() cache 。 cache 1024 , , , , , 。 cache , Cache , 。 Ø blocking: false, true BlockingCache ,blocking, , BlockingCache Key, , , , BlockingCache 。 Ø eviction:eviction, 。 , LRU, LruCache, 1024 Key, , LruCache 。 , , Mybatis Cache 。 LRU , FIFO( , FifoCache)、SOFT( Value, , SoftCache) WEAK( Value, , WeakCache) 。 Ø flushInterval: , , 。 ScheduleCache , flushInterval , , , ScheduleCache 。 Ø readOnly: , false。 false , SerializedCache , , , , , , , , ; true , , , 。 Mybatis , 。 , , , 。 SerializedCache 。 Ø size: Key 。 LruCache ,LruCache 1024 Key, , , eviction , setSize , cache size size 。 Ø type:type , PerpetualCache, Cache, , Cache 。 8.2.2.2cache-ref cache-ref Mapper.xml Cache, Mapper , MapperA MapperB , cache-ref, Key , Key Executor createCacheKey() , BaseExecutor, 。 public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) { if (closed) { throw new ExecutorException("Executor was closed."); } CacheKey cacheKey = new CacheKey(); cacheKey.update(ms.getId()); cacheKey.update(Integer.valueOf(rowBounds.getOffset())); cacheKey.update(Integer.valueOf(rowBounds.getLimit())); cacheKey.update(boundSql.getSql()); List parameterMappings = boundSql.getParameterMappings(); TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry(); // mimic DefaultParameterHandler logic for (int i = 0; i < parameterMappings.size(); i++) { ParameterMapping parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; String propertyName = parameterMapping.getProperty(); if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); value = metaObject.getValue(propertyName); } cacheKey.update(value); } } if (configuration.getEnvironment() != null) { // issue #176 cacheKey.update(configuration.getEnvironment().getId()); } return cacheKey; } PersonMapper.xml UserMapper.xml Cache, cache-ref namespace Cache namespace, UserMapper.xml namespace, UserMapper.xml namespace com.elim.learn.mybatis.dao.UserMapper, PersonMapper.xml cache-ref 。 8.2.3 cache Mybatis Cache PerpetualCache , , , Ehcache、Redis , Cache ,Mybatis , 。 Cache Mybatis Cache , 。 , Cache String , Cache ID, Mybatis Cache , XMLMapperBuilder cacheElement() 。 MyCache 。 /** * @author Elim * 2016 12 20 */ publicclass MyCache implements Cache { private String id; private String name;//Name, , Cache private Map cache = new HashMap(); /** * 。 Cache id * @param id */ public MyCache(String id) { this.id = id; } @Override public String getId() { return this.id; } @Override public void putObject(Object key, Object value) { this.cache.put(key, value); } @Override public Object getObject(Object key) { return this.cache.get(key); } @Override public Object removeObject(Object key) { return this.cache.remove(key); } @Override public void clear() { this.cache.clear(); } @Override public int getSize() { return this.cache.size(); } @Override public ReadWriteLock getReadWriteLock() { return null; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } } Cache Mapper.xml type Cache。 Cache , ,Mybatis set 。 Cache, 。 : : Cache, cache , size、eviction Cache , Cache , Cache, Mybatis Cache , Cache 。 8.2.4 update、insert delete , CachingExecutor update() 。 , flushCache false。 delete t_person where id=#{id} 8.2.5 Cache Mybatis Configuration ,Configuration Mybatis , Mybatis , SqlSession、SqlSessionFactory , Cache。 @Test public void testGetCache() { Configuration configuration = this.session.getConfiguration(); // this.sessionFactory.getConfiguration(); Collection caches = configuration.getCaches(); System.out.println(caches); } 8.2.6 , SqlSession SQL, Cache Mybatis , Cache Mybatis , 。 @Test public void testCache2() { SqlSession session1 = this.sessionFactory.openSession(); SqlSession session2 = this.sessionFactory.openSession(); session1.getMapper(PersonMapper.class).findById(5L); session1.commit(); session2.getMapper(PersonMapper.class).findById(5L); } , session1 SQL session1 commit() , , , , 。 CachingExecutor Mybatis Cache TransactionalCache, Cache , , session1 SQL commit session2 SQL, session1 , ,session2 。

좋은 웹페이지 즐겨찾기