• 16mybatis缓存


    一级缓存
    会话级
    同一个SqlSession接口对象调用相同的select 语句,则直接会从缓存中返回结果,而不是再查询一次数据库
    mybatis 默认情况下,启用一级缓存

    测试代码
    public void one2many(){
    //List<Book> list = bdao.queryAll();

    //System.out.println("--------------------------");
    Book book = bdao.queryById(2);
    System.out.println(book.getName());

    this.ss.clearCache(); //清除一级缓存

    Book b = bdao.queryById(2);
    System.out.println(book==b);
    System.out.println(b.getName());
    System.out.println(b.getPrice());
    }

    二级缓存
    工厂级 全局的,开发者必须自己配置二级缓存
    二级缓存是人工开启的,需要在XxxxMapper.xml 文件中加入如下开启
    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />

    src/main/java/com/fz/mapper/BookMapper.xml 文件

    <?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.fz.mapper.BookMapper">
    <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />
    <resultMap id="book" type="book">
    <id column="book_id" property="id"/>
    <result column="book_name" property="name"/>
    <result column="book_price" property="price"/>
    </resultMap>


    <select id="queryAll" resultMap="book">
    select * from book
    </select>

    <select id="queryById" resultMap="book">
    select * from book where book_id = #{id}
    </select>
    </mapper>

    测试代码:
    @Test
    public void c2(){
    SqlSession s1 = this.sf.openSession();
    SqlSession s2 = this.sf.openSession();

    List<Book> bks = s1.getMapper(BookMapper.class).queryAll();
    s1.commit(); //缓存生效

    List<Book> b2k = s2.getMapper(BookMapper.class).queryAll();

    Book book = s2.getMapper(BookMapper.class).queryById(2);
    Book b2 = s2.getMapper(BookMapper.class).queryById(2);

    //System.out.println(s1==s2);
    //s1.getMapper(BookMapper.class).queryAll();
    //s1.commit();
    //Book b1 = s1.getMapper(BookMapper.class).queryById(2);
    //s1.commit(); //会话一,事务提交缓存生效
    //会话二再查询时就读取了一级缓存
    //Book b2 = s2.getMapper(BookMapper.class).queryById(2);
    }

    怕什么真理无穷,进一步有一步的欢喜
  • 相关阅读:
    java spring-WebSocket json参数传递与接收
    java实现zabbix接口开发
    Linux 系统中的MySQL数据库默认区分大小写
    获取Linux下的IP地址 java代码
    Java多线程问题总结
    Easyui之accordion修改Title样式,字体等
    机器学习算法随机数据生成
    神经网络MPLClassifier分类
    给定数据利用神经网络算法模型进行计算
    vue $refs获取dom元素
  • 原文地址:https://www.cnblogs.com/Mkady/p/7122231.html
Copyright © 2020-2023  润新知