Search code examples
springmybatisspring-mybatis

does mybatis flush cache when execute select ... for update by default?


I know that mybatis has cache, and it will flush cache when execute update by default. So does it flush cache when execute select...for update? If the answer is no, then if I execute select at first, and immediately followed by execute select...for update, the mybatis will access the database or hit the cache?


Solution

  • the cache flush default behavior is not related to the SQL that is actually executed, but to the type of Mybatis statement executed.

    Whatever the SQL is in <select> or @Select then while flushCache property is not specified (into @Options for annotation style), default behavior applies: no flush. and for <update> or @Update cache is flushed by default.

    Anyway in your case, the SELECTand SELECT FOR UPDATE are different SQL strings, then when calling both, the database will be hit for both, even though the resultset is the same, the cache associates the SQL strings and parameters to the result. Change SQL string => new hit, change parameters => new hit. If a statement <select id=stmt1> and another statement <select id=stmt2> produce the same SQL string and are called with same parameter values, during the same session and no flushing operation occurs between them, then the 2nd call should hit the cache. This can be checked by enabling debug logs on mapper.namespace package.

    Cache does not work like in ORM (Hibernate ..): cache referenced by entity type and primary key.

    Cache lasts at most until session ends.

    It is convenient when requesting the same data repeatedly (same statement/parameters) during a session , no need to store result for next use, just call the statement again, cache will just save an access to DB for the result.