MyBatis | Mapping Query Results to Arbitrary Java Objects | Cache

Source code

Main.java

package sample.mybatis;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class Main {

    public static void main(String[] args) throws Exception {
        try (InputStream in = Main.class.getResourceAsStream("/mybatis-config.xml")) {
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);

            try (SqlSession session1 = factory.openSession();
                 SqlSession session2 = factory.openSession();) {

                TestTable testTable = selectAndPrintln("session1", session1);
                testTable.setValue("update");

                selectAndPrintln("session1", session1);

                selectAndPrintln("session2", session2);
            }
        }
    }

    private static TestTable selectAndPrintln(String tag, SqlSession session) {
        TestTable result = session.selectOne("sample.mybatis.selectTest");
        System.out.printf("<<%s>> %s%n", tag, result);
        return result;
    }
}

Execution result

[DEBUG] s.m.selectTest  - ==>  Preparing: select * from test_table where id=1 
[DEBUG] s.m.selectTest  - ==> Parameters: 
[DEBUG] s.m.selectTest  - <==      Total: 1
<<session1>> TestTable [id=1, value=hoge]
<<session1>> TestTable [id=1, value=update]
[DEBUG] s.m.selectTest  - ==>  Preparing: select * from test_table where id=1 
[DEBUG] s.m.selectTest  - ==> Parameters: 
[DEBUG] s.m.selectTest  - <==      Total: 1
<<session2>> TestTable [id=1, value=hoge]

Explanation

  • Query results are cached.
  • If the same query is executed again, the cached object is returned.
  • The cache is stored per session, so it is not affected by changes in another session.
  • The default behavior appears to be as follows.
    • Cache 1024 objects.
    • Remove entries from the least recently used cache.
    • Do not remove entries based on elapsed time.
    • Clear the cache when insert, update, or delete is executed.
  • This default behavior can be overridden in the configuration file.
  • For configuration details, see here.