关于Mybatis的一级缓存和二级缓存的概念以及理解可以参照前面文章的介绍。前文连接:https://www.cnblogs.com/hopeofthevillage/p/11427438.html,上文中二级缓存使用的是xml方式的实现,本文主要是补充一下Mybatis中基于注解的二级缓存的开启使用方法。

  1.在Mybatis的配置文件中开启二级缓存

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!--开启全局的懒加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--&lt;!&ndash;关闭立即加载,其实不用配置,默认为false&ndash;&gt;-->
<!--<setting name="aggressiveLazyLoading" value="false"/>-->
<!--开启Mybatis的sql执行相关信息打印-->
<setting name="logImpl" value="STDOUT_LOGGING" />
<!--默认是开启的,为了加强记忆,还是手动加上这个配置-->
<setting name="cacheEnabled" value="true"/>
</settings>
<typeAliases>
<typeAlias type="com.example.domain.User" alias="user"/>
<package name="com.example.domain"/>
</typeAliases>
<environments default="test">
<environment id="test">
<!--配置事务-->
<transactionManager type="jdbc"></transactionManager>
<!--配置连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test1"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.example.dao"/>
</mappers>
</configuration>

  开启缓存 <setting name="cacheEnabled" value="true"/>,为了查看Mybatis中查询的日志,添加 <setting name="logImpl" value="STDOUT_LOGGING" />开启日志的配置。

  2.领域类以及Dao

public class User implements Serializable{
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
private List<Account> accounts;
省略get和set方法......
} import com.example.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType; import java.util.List;
@CacheNamespace(blocking = true)
public interface UserDao {
/**
* 查找所有用户
* @return
*/
@Select("select * from User")
@Results(id = "userMap",value = {@Result(id = true,column = "id",property = "userId"),
@Result(column = "username",property = "userName"),
@Result(column = "birthday",property = "userBirthday"),
@Result(column = "sex",property = "userSex"),
@Result(column = "address",property = "userAddress"),
@Result(column = "id",property = "accounts",many = @Many(select = "com.example.dao.AccountDao.findAccountByUid",fetchType = FetchType.LAZY))
})
List<User> findAll(); /**
* 保存用户
* @param user
*/
@Insert("insert into user(username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address})")
void saveUser(User user); /**
* 更新用户
* @param user
*/
@Update("update user set username=#{username},birthday=#{birthday},sex=#{sex},address=#{address} where id=#{id}")
void updateUser(User user); /**
* 删除用户
* @param id
*/
@Delete("delete from user where id=#{id}")
void deleteUser(Integer id); /**
* 查询用户根据ID
* @param id
* @return
*/
@Select("select * from user where id=#{id}")
@ResultMap(value = {"userMap"})
User findById(Integer id); /**
* 根据用户名称查询用户
* @param name
* @return
*/
// @Select("select * from user where username like #{name}")
@Select("select * from user where username like '%${value}%'")
List<User> findByUserName(String name); /**
* 查询用户数量
* @return
*/
@Select("select count(*) from user")
int findTotalUser();
}

  3.在对应的Dao类上面增加注释以开启二级缓存 

  @CacheNamespace(blocking = true)

  4.测试

public class UserCacheTest {

    private InputStream in;
private SqlSessionFactory sqlSessionFactory; @Before
public void init()throws Exception{
in = Resources.getResourceAsStream("SqlMapConfig.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); }
@After
public void destory()throws Exception{
in.close();
}
@Test
public void testFindById(){
//第一查询
SqlSession sqlSession1 = sqlSessionFactory.openSession();
UserDao userDao1 = sqlSession1.getMapper(UserDao.class);
User user1 = userDao1.findById(41);
System.out.println(user1);
//关闭一级缓存
sqlSession1.close();
//第二次查询
SqlSession sqlSession2 = sqlSessionFactory.openSession();
UserDao userDao2 = sqlSession2.getMapper(UserDao.class);
User user2 = userDao2.findById(41);
System.out.println(user2);
sqlSession1.close(); System.out.println(user1 == user2);
} }
(1)未开启二级缓存时

(2)开启二级缓存时

 

Mybatis基于注解开启使用二级缓存的更多相关文章

  1. 基于Spring Cache实现二级缓存(Caffeine+Redis)

    一.聊聊什么是硬编码使用缓存? 在学习Spring Cache之前,笔者经常会硬编码的方式使用缓存. 我们来举个实际中的例子,为了提升用户信息的查询效率,我们对用户信息使用了缓存,示例代码如下: @A ...

  2. SpringMVC + ehcache( ehcache-spring-annotations)基于注解的服务器端数据缓存

    背景 声明,如果你不关心java缓存解决方案的全貌,只是急着解决问题,请略过背景部分. 在互联网应用中,由于并发量比传统的企业级应用会高出很多,所以处理大并发的问题就显得尤为重要.在硬件资源一定的情况 ...

  3. 阶段3 1.Mybatis_12.Mybatis注解开发_8 mybatis注解开发使用二级缓存

    执行两次都查询userId为57的数据.测试一级缓存 返回true 新建测试类 ,测试二级缓存 二级缓存的配置 首先是全局配置,不配置其实也是可以的.默认就是开启的.这里为了演示配置上 dao类里面进 ...

  4. MyBatis功能点一:二级缓存cache

    对于Mybatis缓存分作用域等维度区别一.二级缓存特点如下图: 分析缓存源码首先得找到缓存操作的入口:前面已经分析,sqlsesion.close()仅对一级缓存有影响,而update等对一/二级缓 ...

  5. mybatis plus使用redis作为二级缓存

    建议缓存放到 service 层,你可以自定义自己的 BaseServiceImpl 重写注解父类方法,继承自己的实现.为了方便,这里我们将缓存放到mapper层.mybatis-plus整合redi ...

  6. Spring+Mybatis基于注解整合Redis

    基于这段时间折腾redis遇到了各种问题,想着整理一下.本文主要介绍基于Spring+Mybatis以注解的形式整合Redis.废话少说,进入正题. 首先准备Redis,我下的是Windows版,下载 ...

  7. SpringMvc+Spring+MyBatis 基于注解整合

    最近在给学生们讲Spring+Mybatis整合,根据有的学生反映还是基于注解实现整合便于理解,毕竟在先前的工作中团队里还没有人完全舍弃配置文件进行项目开发,由于这两个原因,我索性参考spring官方 ...

  8. Mybatis 源码分析之一二级缓存

    一级缓存 其实关于 Mybatis 的一级缓存是比较抽象的,并没有什么特别的配置,都是在代码中体现出来的. 当调用 Configuration 的 newExecutor 方法来创建 executor ...

  9. java基于注解的redis自动缓存实现

    目的: 对于查询接口所得到的数据,只需要配置注解,就自动存入redis!此后一定时间内,都从redis中获取数据,从而减轻数据库压力. 示例: package com.itliucheng.biz; ...

随机推荐

  1. 虚拟机 vs 容器

    虚拟机 虚拟机本质上是模拟,模拟物理机上的硬件 虚拟机必须安装操作系统 一个虚拟机操作系统的崩溃不会影响到其他虚拟机 容器 容器的本质是经过隔离与限制的linux进程 容器使用的是物理机的资源 容器之 ...

  2. ubuntu开机只有一条横杠在闪的解决办法

    1.制作U盘启动盘,并试用ubuntu 2.输入以下命令,根据提示完成修复 sudo add-apt-repository ppa:yannubuntu/boot-repair && ...

  3. UVA-10462.Is There A Second Way Left(Kruskal+次小生成树)

    题目链接 本题大意:这道题用Kruskal较为容易 参考代码: #include <cstdio> #include <cstring> #include <vector ...

  4. 以区间DP为前提的【洛谷p1063】能量项链

    (跑去练习区间DP,然后从上午拖到下午qwq) 能量项链[题目链接] 然后这道题也是典型的区间DP.因为是项链,所以显然是一个环,然后我们可以仿照石子合并一样,把一个有n个节点的环延长成为有2*n个节 ...

  5. P4514 上帝造题的七分钟(二维树状数组)

    P4514 上帝造题的七分钟 二维树状数组 差分维护区间加法,区间求和 #include<cstdio> int read(){ ,f=; ') f=f&&(c!='-') ...

  6. TypeScript从入门到Vue项目迁移

    1. 前言 ES6的普及,大大简化了JavaScript的表达方式 大型项目中,js没有类型检查.表达方式灵活,多人协作代码调试和维护成本高 2. 定义 TypeScript 是 JavaScript ...

  7. ES6——Promise

    异步和同步 异步,操作之间没有关系,同时执行多个操作, 代码复杂 同步,同时只能做一件事,代码简单 Promise 对象 用同步的方式来书写异步代码 Promise 让异步操作写起来,像在写同步操作的 ...

  8. ORI-621龙芯3A处理器CPCI刀片计算机

    ORI-621龙芯3A处理器CPCI刀片计算机 一.产品简介 ORI -621是一款基于龙芯3A国产CPU处理器的特种CPCI刀片计算机.该产品成功地实现了服务器NUMA架构在国产特种计算机中的应用, ...

  9. react依赖注入之mapStateToProps&&mapDispatchToProps

    今天看前辈写的代码,看到mapStateToProps&&mapDispatchToProps处,不明白,于是又是各种找资料,在CSDN博客中发现一篇好文,摘抄到此,方便自己阅读! 原 ...

  10. Could not resolve all files for configuration ':app:debugCompileClasspath'.解决方案

    异常如下: Error:FAILURE: Build failed with an exception. * What went wrong:Could not resolve all files f ...