关于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. Node.js实战7:你了解buffer吗?

    Buffer是NodeJS的重要数据类型,很有广泛的应用. Buffer是代表原始堆的分配额的数据类型.在NodeJS中以类数组的方式使用. 比如,用法示例: var buf = new Buffer ...

  2. 触摸板PCB制作-TM12

    1.布局: 使 PSoC 与Sensor之间的距离保持最小化是一个不错的做法. 通常将 PSoC 与其他组件一起贴装到底层,而将 CapSense Sensor置于顶层上.  Sensor和栅格地层位 ...

  3. Java-Lambda表达式第二篇认识Lambda表达式

    接上面的方法引用和构造器引用: 3>引用某类对象的实例方法 @FunctionalInterface public interface Cut{ String cut(String str,in ...

  4. 第二次java面试(用友山东济南分公司)

    坐标:山东潍坊公共实训基地 面试单位:用友济南分公司(来了一位HR和技术经理) 本人状态:距离离校15天 宣讲: 1.女HR和男技术经理来到我们专业提前准备好的教室,先宣传海报和发传单,然后看了4个3 ...

  5. 旧接口注册LED字符驱动设备(动态映射)

    #include <linux/init.h> // __init __exit #include <linux/module.h> // module_init module ...

  6. BZOJ 4552(二分+线段树+思维)

    题面 传送门 分析 此题是道好题! 首先要跳出思维定势,不是去想如何用数据结构去直接维护排序过程,而是尝试二分a[p]的值 设二分a[p]的值为x 我们将大于x的数标记为1,小于等于x的数标记为0 则 ...

  7. 2019 Multi-University Training Contest 3 - 1006 - Fansblog - 打表 - 暴力

    http://acm.hdu.edu.cn/showproblem.php?pid=6608 题意:给一个比较大的质数P(1e14以内),求比它小的最大的质数Q(貌似保证存在的样子,反正我没判不存在) ...

  8. [WPF自定义控件库] 关于ScrollViewer和滚动轮劫持(scroll-wheel-hijack)

    原文:[WPF自定义控件库] 关于ScrollViewer和滚动轮劫持(scroll-wheel-hijack) 1. 什么是滚动轮劫持# 这篇文章介绍一个很简单的继承自ScrollViewer的控件 ...

  9. TP中如何去掉index.php

    使用过TP的同学都知道,在URL始终会有index .php  我们如何才能够去掉呢? 1. 确认httpd.conf配置文件中加载了mod_rewrite.so模块 2. AllowOverride ...

  10. typescript总结

    1,基础类型 {   布尔值,let isDone:Boolean=true;   数字,let decLiteral:number=true;   字符串,let name:string=" ...