Mybatis的缓存

缓存也是为了减少java应用与数据库的交互次数,提升程序的效率

一级缓存

自带一级缓存,并且无法关闭,一直存在,存储在SqlSession中

使用同一个sqlsession进行查询操作一级缓存存在;如果有多个sqlsession那么一级缓存不存在

缓存一般争对查询,如果进行了增删改查操作,会自动的将缓存的数据清除,保证数据的一致性,一级缓存不需要设置,直接使用即可。

1.实体类

package com.shouthwind.entity;

import lombok.Data;

import java.util.List;

@Data
public class Account {
private Integer id;
private String name;
private List<Course> courses;
}

2.接口

package com.shouthwind.repository;

import com.shouthwind.entity.Account;

public interface AccountRepository {
public Account findById1(Integer id);
public Account findById(Integer id);
}

3.Mapper

<?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.shouthwind.repository.AccountRepository">
<resultMap id="accoutMap" type="com.shouthwind.entity.Account">
<id column="aid" property="id"></id>
<result column="aname" property="name"></result>
<collection property="courses" ofType="com.shouthwind.entity.Course">
<id column="cid" property="id"></id>
<result column="cname" property="name"></result>
</collection>
</resultMap>
<select id="findById1" parameterType="java.lang.Integer" resultMap="accoutMap">
select a.id aid,a.name aname,c.id cid,c.name cname from account a,t_course c,account_course ac where a.id=#{id} and a.id=ac.aid and c.id=ac.cid
</select>
<select id="findById" parameterType="java.lang.Integer" resultType="com.shouthwind.entity.Account">
select * from account where id=#{id}
</select>
</mapper>

4.测试

对一个SQL session一直使用查询的结果

二级缓存

它是Mapper级别的,无论使用多少个sqlsession都可以共享。

二级缓存默认是关闭的,二级缓存配置开启。

  • 自带的二级缓存
  • 第三方的ehcache二级缓存

自带的二级缓存

1.配置config.xml

<!--        打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>

2.Mapper.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.shouthwind.repository.StudentRepository"> <cache></cache> <resultMap id="studentMap" type="com.shouthwind.entity.Student">
<id column="sSno" property="Sno"></id>
<result column="sSname" property="Sname"></result>
<result column="sSsex" property="Ssex"></result>
<result column="sSage" property="Sage"></result>
<result column="sSdept" property="Sdept"></result>
<association property="sc" javaType="com.shouthwind.entity.Sc">
<result column="cSno" property= "Sno"></result>
<result column="cCno" property="Cno"></result>
<result column="cGrade" property="Grade"></result>
</association>
</resultMap>
<select id="findById" parameterType="java.lang.Integer" resultMap="studentMap">
select s.Sno sSno,s.Sname sSname,s.Ssex sSsex,s.Sage sSage,s.Sdept sSdept,c.Sno cSno,c.Cno cCno,c.Grade cGrade from student s,sc c where s.Sno=c.Sno and s.Sno=#{Sno}
</select>
</mapper>

3.实体类实现Serializable接口

package com.shouthwind.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class Student implements Serializable {
private Integer Sno;
private String Sname;
private String Ssex;
private Integer Sage;
private String Sdept;
private Sc sc;
}

第三方的ehcache缓存

1.配置

<!--        ehcache-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>

2.在resource小创建ehcache创建配置

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘保存路径 -->
<diskStore path="D:\\ehcache" /> <defaultCache
maxElementsInMemory="10000"
maxElementsOnDisk="10000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
</defaultCache>
</ehcache>

3.config.xml中配置二级缓存

    <settings>
<!-- 打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- 延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!-- 开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>

4.Mapper.xml中配置二级缓存

    <cache type="org.mybatis.caches.ehcache.EhcacheCache">
<!-- 缓存创建以后,最后一次访问的时间到失效时间-->
<property name="timeToIdleSeconds" value="3600"/>
<!-- 缓存自创建时间起自失效时间的间隔-->
<property name="timeToLiveSeconds" value="3600"/>
<!-- 缓存回收策略,LRU移除近期的最少使用的对象-->
<property name="memoryStoreEvictionPolicy" value="LRU"/>
</cache>

5.实体类不需要实现序列化接口

Mysql的动态SQL

Mybatis的动态SQL可以更据不同的信息来拼接不同的SQL、以适应不同的需求

1.创建实体类

package com.shouthwind.entity;

import lombok.Data;

@Data
public class People {
// private Integer Sno;
// private String Sname;
// private String Ssex;
// private Integer Sage;
// private String Sdept;
private Integer id;
private String name;
private Integer money;
}

2.创建Mapper接口和文件

package com.shouthwind.repository;

import com.shouthwind.entity.People;

import java.util.List;

public interface UserRepository {
// public int save(People people);
// public int deleteById(Integer id);
// public int update(People people);
// public People findById(Integer id);
// public List<People> findAll();
// public People findById2(int id);
// public People findByName(String name);
// public People findByIdAndName(Integer id,String name);
// public Integer count();
// public String findNameById(Integer id);
public People findByUser (People people);
}
<!--    动态  sql-->
<select id="findByUser" parameterType="com.shouthwind.entity.People" resultType="com.shouthwind.entity.People">
select * from people
<where>
<if test="id!=null">
id=#{id}
</if>
<if test="name!=null">
and name={name}
</if>
<if test="money!=null">
and money=#{money}
</if>
</where>
</select>

4.测试

package com.shouthwind.Test;

import com.shouthwind.entity.People;
import com.shouthwind.repository.UserRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class Test7 {
public static void main(String[] args) {
InputStream inputStream = Test7.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取实现了自定义代理接口的对象
UserRepository userRepository=sqlSession.getMapper(UserRepository.class);
People people = new People();
people.setId(1);
People result =userRepository.findByUser(people);
System.out.println(result);
}
}

if

where

  • choose、when

    类似swich case

代码:

<!--    动态  sql-->
<select id="findByUser" parameterType="com.shouthwind.entity.People" resultType="com.shouthwind.entity.People">
select * from people
<where>
<choose>
<when test="id!=null">
id=#{id}
</when>
<when test="name!=null">
and name={name}
</when>
<when test="money!=null">
and money=#{money}
</when>
</choose>
</where>
</select>
  • trim

    设置predix和suffix参数来完成使用

    <!--    动态  sql-->
    <select id="findByUser" parameterType="com.shouthwind.entity.People" resultType="com.shouthwind.entity.People">
    select * from people
    <trim prefix="where" prefixOverrides="and">
    <choose>
    <when test="id!=null">
    id=#{id}
    </when>
    <when test="name!=null">
    and name={name}
    </when>
    <when test="money!=null">
    and money=#{money}
    </when>
    </choose>
    </trim>
    </select>
  • set用于update操作

    package com.shouthwind.repository;
    
    import com.shouthwind.entity.People;
    
    import java.util.List;
    
    public interface UserRepository {
    // public int save(People people);
    // public int deleteById(Integer id);
    // public int update(People people);
    // public People findById(Integer id);
    // public List<People> findAll();
    // public People findById2(int id);
    // public People findByName(String name);
    // public People findByIdAndName(Integer id,String name);
    // public Integer count();
    // public String findNameById(Integer id);
    public People findByUser (People people);
    public Integer update (People people);
    }

    mapperi文件

    <update id="update" parameterType="com.shouthwind.entity.People">
    update people
    <set>
    <if test="name!=null">
    name=#{name},
    </if>
    <if test="money!=null">
    money=#{money}
    </if>
    </set>
    where id=#{id}
    </update>

测试类:

package com.shouthwind.Test;

import com.shouthwind.entity.People;
import com.shouthwind.repository.UserRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class Test7 {
public static void main(String[] args) {
InputStream inputStream = Test7.class.getClassLoader().getResourceAsStream("config.xml");
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取实现了自定义代理接口的对象
UserRepository userRepository=sqlSession.getMapper(UserRepository.class);
People people = new People();
people.setId(1);
people.setName("郝momo");
people.setMoney(55);
userRepository.update(people);
sqlSession.commit();
// People result =userRepository.findByUser(people);
// System.out.println(result);
sqlSession.close();
}
}

Mybatis的缓存与动态SQL的更多相关文章

  1. MyBatis学习总结_11_MyBatis动态Sql语句

    MyBatis中对数据库的操作,有时要带一些条件,因此动态SQL语句非常有必要,下面就主要来讲讲几个常用的动态SQL语句的语法 MyBatis中用于实现动态SQL的元素主要有: if choose(w ...

  2. MyBatis:学习笔记(4)——动态SQL

    MyBatis:学习笔记(4)——动态SQL

  3. SSM框架之Mybatis(6)动态SQL

    Mybatis(6)动态SQL 1.动态SQL 出现原因:有些时候业务逻辑复杂时,我们的 SQL 是动态变化的,此时在前面的学习中我们的 SQL 就不能满足要求了 1.1.if标签 我们根据实体类的不 ...

  4. Spring mybatis源码篇章-动态SQL节点源码深入

    通过阅读源码对实现机制进行了解有利于陶冶情操,承接前文Spring mybatis源码篇章-动态SQL基础语法以及原理 前话 前文描述到通过mybatis默认的解析驱动类org.apache.ibat ...

  5. MyBatis(三)动态SQL与缓存

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 一.动态SQL语句 准备工作: public class User { private int id; ...

  6. MyBatis学习06(动态SQL和缓存)

    10.动态SQL 10.1 什么是动态SQL 动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句. 官网描述: MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或 ...

  7. Mybatis系列全解(八):Mybatis的9大动态SQL标签你知道几个?提前致女神!

    封面:洛小汐 作者:潘潘 2021年,仰望天空,脚踏实地. 这算是春节后首篇 Mybatis 文了~ 跨了个年感觉写了有半个世纪 ... 借着女神节 ヾ(◍°∇°◍)ノ゙ 提前祝男神女神们越靓越富越嗨 ...

  8. mybatis入门基础(五)----动态SQL

    一:动态SQL 1.1.定义 mybatis核心对sql语句进行灵活操作,通过表达式进行判断,对sql进行灵活拼接.组装. 1.2.案例需求 用户信息综合查询列表这个statement的定义使用动态s ...

  9. (转)Mybatis高级映射、动态SQL及获得自增主键

    原文:http://www.cnblogs.com/edwinchen/p/4105278.html?utm_source=tuicool&utm_medium=referral 一.动态SQ ...

  10. Mybatis高级映射、动态SQL及获得自增主键

    一.动态SQL 相信大家在用mybatis操作数据库时时都会碰到一个问题,假如现在我们有一个关于作者的list authorList,需要根据authorList里已有的作者信息在数据库中查询相应作者 ...

随机推荐

  1. 1759E(方案枚举)

    题目链接 题目大意: 给你n个数(n个宇航员对应的能量值) 一个h ,h表示机器人当前的能量值.机器人拥有2中绿色的药剂,一瓶蓝色的药剂.其中绿色的药剂可以使机器人的能量值变为现在的2倍(2-> ...

  2. NOI2011真题:兔兔与蛋蛋游戏

    NOI2011真题:兔兔与蛋蛋游戏 题目描述 这些天,兔兔和蛋蛋喜欢上了一种新的棋类游戏. 这个游戏是在一个 n行 m 列的棋盘上进行的.游戏开始之前,棋盘上有一个格子是空的,其它的格子中都放置了一枚 ...

  3. nc传输文件结束后不退出

    原因 版本不同 udp传输不会自动关闭 解决方案 nc -l 1234 > file.img nc ip 1234 -q 0 < file.img 采用tcp传输文件 -q 文件传输结束后 ...

  4. 关于python实现与体重秤蓝牙ble通信研究(Linux)

    前言 前几天买一个带蓝牙的体重秤,功能就是可以通过手机app连接,然后每一次称重都会记录下来,然后进行一些计算(体脂等),但是我不想用手机来操作,我习惯用电脑,就想写一个软件来与体重秤通信,记录我的每 ...

  5. 【Kafka】Quota配额命令、文档相关概念

    一.多租赁模式基于 Zookeeper和 kafka-configs.sh 管理所有用户 1.步骤 l 基于zookeeper,实现用户管理 l 配置broker认证信息,并进行平滑更新 l 配置cl ...

  6. 提高python异步效率

    uvloop #Python标准库中提供了asyncio模块,用于支持基于协程的异步编程. #uvloop是 asyncio 中的事件循环的替代方案,替换后可以使得asyncio性能提高.事实上,uv ...

  7. 文件压缩和vi编辑器

    一.压缩,解压缩 1.gzip 和 bzip2 gzip和bzip都是压缩软件,比如windows里的好压和360 压缩或微软自带的等等 命令格式是:gzip或者bzip  + 0-9的压缩等级(数字 ...

  8. 【Java面试指北】反射(1) 初识反射

    如果你被问到:什么是反射?为什么需要反射.以及反射的应用?你会如何回答呢? 本篇会带大家初识反射,了解反射概念和基本应用.反射的原理以及深入源码的探究将会在后面几篇介绍. 一.什么是反射? 要理解什么 ...

  9. 如何优化大场景实时渲染?HMS Core 3D Engine这么做

    在先前举办的华为开发者大会2022(HDC)上,华为通过3D数字溪村展示了自有3D引擎"HMS Core 3D Engine"(以下简称3D Engine)的强大能力.作为一款高性 ...

  10. ArcObjects SDK开发 021 开发框架搭建-FrameWork包设计

    1.框架引擎部分 引擎模块其实就是之前我们说的App-Command-Tool模块,通过这个模块,把系统的主干框架搭建起来. 其中大部分出现在菜单以及工具条上的按钮都会继承这个框架定义ICommand ...