search
HomeJavajavaTutorialHow to use the second-level cache of Mybatis in Java

    Overview and classification of cache

    Overview

    Cache is a piece of memory space that saves temporary data

    Why use Cache

    Read the data from the data source (database or file) and store it in the cache. When retrieving it, obtain it directly from the cache, which can reduce the number of interactions with the database, which can improve the performance of the program. Performance!

    Applicability of cache

    Suitable for cache: frequently queried but not frequently modified (eg: provinces, cities, category data), the accuracy of the data has no impact on the final result Big

    Not suitable for caching: frequently changing data, sensitive data (for example: stock market prices, bank exchange rates, money in bank cards), etc.

    MyBatis Cache Category

    Level 1 cache: It is the cache of the sqlSession object. It comes with it (no configuration required) and cannot be uninstalled (if you don’t want to use it). The life cycle of the first level cache is consistent with sqlSession.

    Second level cache: It is the cache of SqlSessionFactory. As long as the SqlSession created by the same SqlSessionFactory shares the contents of the second-level cache, it can operate the second-level cache. If we want to use the second-level cache, we need to manually enable it ourselves (configuration is required).

    Use of second-level cache

    1. Enable the second-level cache in the core configuration file of mybatis

        <!--**因为 cacheEnabled 的取值默认就为 true**,所以这一步可以省略不配置。为 true 代表开启二级缓存;为 false 代表不开启二级缓存。  -->
    <settings>
        <setting name="cacheEnabled" value="true"/>
    </settings>

    2. Configure the use of the second-level cache in the Dao mapping file

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.itheima.dao.UserDao">
        <!--配置二级缓存-->
        <cache/>
       
        <select id="findAll" resultType="user">
            select * from t_user
        </select>
     
        <delete id="deleteById" parameterType="int">
            delete from t_user where uid=#{id}
        </delete>
    </mapper>

    3. The Pojo class for second-level caching must implement the Serializable interface

    public class User implements Serializable {
        private int uid;
        private String username;
        private String sex;
        private Date birthday;
        private String address;
        // 省略setter,getter,构造...等方法
    }

    4. Test the use of second-level cache

    Test code

    @Test
          public void testFindAll() throws Exception{
              // 1.加载mybatis核心配置文件
              InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
     
              // 2.创建SqlSessionFactoryBuilder对象
              SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
     
              // 3.构建SqlSessionFactory对象
              SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
     
              // 4.获取SqlSession对象
              SqlSession sqlSession = sqlSessionFactory.openSession();
     
              // 5.获得dao接口的代理对象
              UserDao userDao = sqlSession.getMapper(UserDao.class);
     
              // 6.执行sql语句,得到结果
              List<User> list = userDao.findAll();
              for (User user : list) {
                  System.out.println("user = " + user);
              }
              sqlSession.close();//清除一级缓存
     
              System.out.println("分割线----------------------------------");
     
              SqlSession sqlSession2 = sqlSessionFactory.openSession();
              UserDao userDao2 = sqlSession2.getMapper(UserDao.class);
              List<User> userList2 = userDao2.findAll();
              for (User user : userList2) {
                  System.out.println(user);
              }
              // 7.释放资源
              sqlSession2.close();
          }

    - Test results:

    How to use the second-level cache of Mybatis in Java

    #- After the above test, we found that two queries were executed, and after executing the first query, we turned off the first-level cache and then went to When executing the second query, we found that no SQL statement was issued to the database, so the data at this time can only come from what we call the second-level cache.

    5. Test to turn off the second-level cache

    -Test code

       @Test
          public void testFindAll() throws Exception{
              // 1.加载mybatis核心配置文件
              InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
     
              // 2.创建SqlSessionFactoryBuilder对象
              SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
     
              // 3.构建SqlSessionFactory对象
              SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
     
              // 4.获取SqlSession对象
              SqlSession sqlSession = sqlSessionFactory.openSession();
     
              // 5.获得dao接口的代理对象
              UserDao userDao = sqlSession.getMapper(UserDao.class);
     
              // 6.执行sql语句,得到结果
              List<User> list = userDao.findAll();
              for (User user : list) {
                  System.out.println("user = " + user);
              }
              sqlSession.close();//清除一级缓存
     
              System.out.println("分割线----------------------------------");
     
              SqlSession sqlSession2 = sqlSessionFactory.openSession();
              UserDao userDao2 = sqlSession2.getMapper(UserDao.class);
              userDao2.deleteById(5);// 关闭二级缓存
     
              List<User> userList2 = userDao2.findAll();
              for (User user : userList2) {
                  System.out.println(user);
              }
              // 7.释放资源
              sqlSession2.close();
          }

    -Test result

    How to use the second-level cache of Mybatis in Java

    After the above Testing, we found that two queries were executed, and after executing the first query, we closed the first-level cache and the second-level cache. When we executed the second query, we found that a sql statement was issued to the database, so The data at this time comes from the database, not the cache.

    The above is the detailed content of How to use the second-level cache of Mybatis in Java. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

    Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

    What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

    JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

    Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

    ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

    What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

    Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

    What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

    Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

    How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

    JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

    How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

    The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

    Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

    The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    Atom editor mac version download

    Atom editor mac version download

    The most popular open source editor