Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize the first-level cache and second-level cache of Mybatis

Shulou Source: shulou.com Published: 2022-06-01 12:58:38 09月30日 Update

This article mainly shows you "how to achieve Mybatis first-level cache and second-level cache", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to achieve Mybatis first-level cache and second-level cache" this article.

Mybatis caching

Mybatis as a popular persistence tool, caching must be an indispensable component. Through this article, let's take a look at mybatis caching.

Mybatis cache type

Speaking of mybatis caching, all students know that there are two cache types in mybatis:

First, we often call it and caching, or sqlSession-level caching, which is included with mybatis. If the configuration in mapper is default, first-level caching is also enabled by default.

The second is non-sqlSession-level cache, which is commonly called secondary cache. Secondary cache in mybatis needs to implement the Cache API and is configured in mapper. To enable it first, some configuration is required, which we will talk about in detail below.

First-level cache

As the cache that comes with mybatis, let's analyze its principle through code.

First, let's look at the effect of the next level of caching.

Test the code:

@ Testpublic void test_Cache () throws Exception {InputStream input = Resources.getResourceAsStream ("mybatis-config.xml"); SqlSessionFactory factory = new SqlSessionFactoryBuilder () .build (input); SqlSession sqlSession = factory.openSession (); UserMapper mapper = sqlSession.getMapper (UserMapper.class); System.out.println ("the first query:"); mapper.queryAllUsers (); System.out.println ("= ="); System.out.println ("the second query:"); mapper.queryAllUsers () SqlSession.commit ();}

The mapper configuration is as follows, and we use the default configuration:

Select * from hwc_users

The running results are as follows:

Created connection 1191654595.

Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@470734c3]

= > Preparing: select * from hwc_users

= > Parameters:

Tags: Cache Hu Wen configuration code results queries properties processing that is data files articles content objects databases modules types projects storage Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi macOS MariaDB Apple OPPO Reno