Mybatis缓存

------------恢复内容开始------------

延迟加载(需要的时候再加载)

 1.一对一延迟加载:一个账户(Account)对应一个用户(User),配置如下:

  在核心配置文件中打开延迟加载,注意settings标签的位置,在properties标签和typeAliases之间,顺序不对会报错。

 <!--配置settings-->
    <settings>
        <!--开启延迟加载-->
        <setting name="lazyLoadingEnabled" value="true"></setting>
        <setting name="aggressiveLazyLoading" value="false"></setting>
    </settings>

  在Account映射文件中配置封装:

<!--对account对象的封装,每个account对象中有一个User对象作为属性-->
    <resultMap id="accountUserMap" type="com.itheima.domain.Account">
        <!--这里的aid是sql语句查询时使用的别名,同时这里的id标签和下面的id标签应该都可以换成result标签-->
        <id property="id" column="id"></id>
        <result property="uid" column="uid"></result>
        <result property="money" column="money"></result>
        <!--配置一对一关系,对User对象的封装 assocaiation中的,
            select参数是UserDao映射文件中的查询语句
            这里的column必须要
            uid就是findById所需要的参数
        -->
        <association property="user" column="uid"
                     javaType="com.itheima.domain.User"
                     select="com.itheima.dao.IUserDao.findById">
        </association>
    </resultMap>

    <!--id为接口中的方法名-->
    <select id="findAll" resultMap="accountUserMap">
        select * from account;
    </select>

 2.一对多延迟加载:一个用户(User)对应多个角色(Role)

  在User映射文件中配置封装:操作都是差不多的,只是有一些配置与一对一不同

<resultMap id="UserMap" type="com.itheima.domain.User">
        <id property="id" column="id"></id>
        <result property="username" column="username"></result>
        <result property="birthday" column="birthday"></result>
        <result property="sex" column="sex"></result>
        <result property="address" column="address"></result>
        <!--配置一对多延迟加载  column中的id就是上面user的id-->
        <collection property="accounts" ofType="com.itheima.domain.Account"
                    select="com.itheima.dao.IAccountDao.findByUid" column="id">
        </collection>
    </resultMap>

    <select id="findAllUser" resultMap="UserMap">
        select * from user;
    </select>

 Mybatis中的缓存

  缓存就是存放在内存中的临时数据,使用缓存库减少与数据库的交互次数,从而提高效率,缓存用户存放一些不经常改变,但经常需要查询的数据。

 1.一级缓存

  指的是mybatis中SqlSession对象的缓存,当我们执行查询之后,查询结果(封装为对象的数据)会同时存放到SqlSession为我们提供的一块区域中,该区域的结构嗨哟个Map,当我们再次查询的时候,mybatis会先去SqlSession中查询是否有,有的话就直接拿出来用。

  一级缓存会在调用SQLSession的修改,添加,删除,commit(),close(),等方法时清空。

 2.二级缓存

  二级缓存指的是Mybatis中SqlSessionFactory对象的缓存,由同一个SqlSessionFactory创建的SqlSession对象共享同一块缓存区。二级缓存中存放的是数据(json格式的数据),而不是对象

  使用步骤:

   1.让Mybatis框架支持二级缓存(在核心配置文件中配置)

<settings>
        <!--开启二级缓存-->
        <setting name="cacheEnabled" value="true"></setting>
    </settings>

   2.让当前的映射文件支持缓存(在IUserDao.xml中配置)

    在映射文件中加入一个<cache/>标签就行了

   3.让当前的操作支持缓存(在select标签中配置)

    在select标签中添加userCache="true"参数

原文地址:https://www.cnblogs.com/zy-Luo/p/11782910.html