Java(Mybatis03)

Java(Mybatis03)

参考视频:22. 动态SQL环境搭建(狂神)

12. 动态SQL

  • 什么是动态sql:动态sql就是根据不同的条件生成不同的sql语句。
  • 利用动态SQL这一特性可以“摆脱”这种痛苦…
    • if
    • choose (when, otherwise)
    • trim (where, set)
    • foreach
  • 如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

12.1 搭建环境

  • sql
CREATE TABLE `blog`(
	`id`          VARCHAR(50)  NOT NULL COMMENT '博客id',
	`title`       VARCHAR(100) NOT NULL COMMENT '博客标题',
	`author`      VARCHAR(30)  NOT NULL COMMENT '博客作者',
	`create_time` DATETIME     NOT NULL COMMENT '创建时间',
	`views`       INT(30)      NOT NULL COMMENT '浏览量'
)ENGINE = INNODB DEFAULT CHARSET = utf8;
  • 创建一个基础工程
  1. 导包
  2. 编写配置文件
  3. 编写实体类
package com.zach.pojo;

import lombok.Data;

import java.util.Date;

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;//属性名和字段名不一致
    private int views;
}
  1. 编写实体类对应的Mapper接口 和 Mapper.xml文件
  • BlogMapper
package com.zach.dao;

import com.zach.pojo.Blog;

public interface BlogMapper {
    //插入数据
    int addBlog(Blog blog);
}
  • BlogMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
		PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.zach.dao.BlogMapper">

	<!--insert-->
	<insert id="addBlog" parameterType="blog">
		insert into blog (id, title, author, create_time, views)
		values (#{id},#{title},#{author},#{createTime},#{views});
	</insert>
	
</mapper>
  • IDutils
package com.zach.pojo;

import org.junit.Test;

import java.util.UUID;

@SuppressWarnings("all")//抑制警告
public class IDutils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}
  • mybatis-config.xml(修改)
	<mappers>
		<mapper class="com.zach.dao.BlogMapper"/>
	</mappers>
  • MyTest - addInitBlog()
    @Test
    public void addInitBlog(){
        SqlSession session = MybatisUtils.getSqlSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        
        Blog blog = new Blog();
        blog.setId(IDutils.getId());
        blog.setTitle("Mybatis如此简单");
        blog.setAuthor("狂神说");
        blog.setCreateTime(new Date());
        blog.setViews (9999) ;
        
        mapper.addBlog(blog);
        
        blog.setId(IDutils.getId());
        blog.setTitle("Java如此简单");
        mapper.addBlog(blog);
        
        blog.setId(IDutils.getId());
        blog.setTitle("Spring如此简单");
        mapper.addBlog(blog);
        
        blog.setId(IDutils.getId());
        blog.setTitle("微服务如此简单");
        mapper.addBlog(blog);
        
        session.close();
    }

12.2 if

  • BlogMapper
    //查询博客
    List<Blog> queryBlogIF(Map map);
  • BlogMapper.xml
	<select id="queryBlogIF" parameterType="map" resultType="blog">
		select *
		from blog
		where 1=1
		<if test="title != null">
			and title = #{title}
		</if>
		<if test="author != null">
			and author = #{author}
		</if>
	</select>
  • MyTest
    @Test
    public void queryBlogIF(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    
        HashMap map = new HashMap();
//        map.put("title","Java如此简单");
        map.put("author","狂神说");
        
        List<Blog> blogs = mapper.queryBlogIF(map);
    
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        
        sqlSession.close();
    }

12.3 choose(when,otherwise)

  • BlogMapper
    //查询博客2
    List<Blog> queryBlogChoose(Map map);
  • BlogMapper.xml
	<select id="queryBlogChoose" parameterType="map" resultType="blog">
		select *
		from blog
		<where>
			<choose>
				<when test="title != null">
					title = #{title}
				</when>
				<when test="author != null">
					author = #{author}
				</when>
				<otherwise>
					views = #{views}
				</otherwise>
			</choose>
		</where>
	</select>
  • MyTest
    @Test
    public void queryBlogChoose(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        
        HashMap map = new HashMap();
//        map.put("title","Java如此简单");
//        map.put("author","狂神说");
        map.put("views",9999);
        
        List<Blog> blogs = mapper.queryBlogChoose(map);
        
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        
        sqlSession.close();
    }

12.4 trim(where,set)

  • where
  • BlogMapper.xml
	<select id="queryBlogIF" parameterType="map" resultType="blog">
		select *
		from blog
		<where>
			<if test="title != null">
				title = #{title}
			</if>
			<if test="author != null">
				and author = #{author}
			</if>
		</where>
	</select>
  • set
  • BlogMapper.xml
	<select id="updateBlog" parameterType="map">
		update blog
		<set>
			<if test="title != null">
				title = #{title},
			</if>
		    <if test="author != null">
				author = #{author}
		    </if>
		</set>
		<where>
			id = #{id}
		</where>
	</select> 
  • trim
  • where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
  • 如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
  ...
</trim>
  • prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
  • 用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:
<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>
  • 这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
  • 或者,你可以通过使用trim元素来达到同样的效果:
<trim prefix="SET" suffixOverrides=",">
  ...
</trim>
  • 注意,我们覆盖了后缀值设置,并且自定义了前缀值。

  • 所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面,去执行一个逻辑代码。

12.5 SQL片段

  • 有的时候,我们可能会将一些功能的部分抽取出来,方便复用。
  1. 使用SQL标签抽取公共的部分
	<!--sql标签-->
	<sql id="if-title-author">
		<if test="title != null">
			title = #{title}
		</if>
		<if test="author != null">
			and author = #{author}
		</if>
	</sql>
  1. 在需要使用的地方使用include标签引用即可
	<!--使用sql标签后-->
	<select id="queryBlogIF" parameterType="map" resultType="blog">
		select *
		from blog
		<where>
			<include refid="if-title-author"></include>
		</where>
	</select>
  • 注意事项:
    • 最好基于单表来定义SQL片段!
    • 不要存在where标签!

12.6 foreach

select * from user where 1=1 and
	<foreach item="id" colliection="ids"
		open="(" separator="or" close=")">
			#{id}
	</foreach>

(id=1 or id=2 or id=3)

在这里插入图片描述

  • BlogMapper.xml
	<!--
		select * from blog where 1=1 and (id=1 or id=2 or id=3);
		我们现在传递一个万能的map,这个map中可以存在一个集合!
	-->
	<select id="queryBlogForeach" parameterType="map" resultType="blog">
		select *
		from blog
		<where>
			<foreach collection="ids" item="id" open="and (" close=")" separator="or">
				id = #{id}
			</foreach>
		</where>;
	</select>
  • 动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
  • 建议:
    • 先在mysql中写出完整的SQL语句,再去对应地修改成我们需要的动态SQL,实现通用即可。

13. 缓存(了解)

13.1 简介

  • 什么是缓存(cache)?
    • 存在内存中的临时数据。
    • 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。
  • 为什么使用缓存?
    • 减少和数据库的交互次数,减少系统开销,提高系统效率
  • 什么样的数据能使用缓存?
    • 经常查询并且不经常改变的数据。

13.2 Mybatis缓存

  • mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提高查询效率。
  • mybatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启。(sqlsession级别的缓存,也称为本地缓存)
    • 二级缓存需要手动开启和配置,它是基于namespace级别的缓存。
    • 为了提高扩展性,mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。

13.3 一级缓存

  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放到本次缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库。

  • 测试步骤:
  1. 开启日志
  • mybatis-config.xml
	<!--日志-->
	<settings>
		<!--标准的日志工厂实现-->
		<setting name="logImpl" value="STDOUT_LOGGING"/>
	</settings>
  1. 测试再一个session中查询两次相同的记录
    @Test
    public void test(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        User user = mapper.queryUserById(1);
        System.out.println(user);
    
        System.out.println("=========================");
        
        User user2 = mapper.queryUserById(1);
        System.out.println(user2);
    
        System.out.println(user==user2);
        
        sqlSession.close();
    }
  1. 查看日志输出
    在这里插入图片描述
  • 缓存失效的情况:
  • 查询不同的东西。
  • 增删改操作,涉及到改变了数据库的操作,必须刷新缓存:
    在这里插入图片描述
  • 查询不同的Mapper.xml(也是查询不同的东西)。
  • 手动清理缓存:
    在这里插入图片描述
  • 小结:
    • 一级缓存默认开启,只在一次SqlSession中有效,也就是拿到连接直到关闭连接这个区间段。
    • 一级缓存就是一个Map。

13.4 二级缓存

  • 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。
  • 基本namespace级别的缓存,一个名称空间,对应一个二级缓存。
  • 工作机制:
    • 一个会话查询一个数据,这个数据就会被放到当前会话的一级缓存中。
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中。
    • 新的会话查询信息,就可以直接从二级缓存中获取内容。
    • 不同的mapper查出的数据会放在自己对应的缓存(map)中。

  • 开启二级缓存步骤:
  1. 开启全局缓存:
  • mybatis-config.xml
		<!--显式地开启全局缓存-->
		<setting name="cacheEnabled" value="true"/>
  1. 在要使用二级缓存的Mapper中开启
	<!--在当前Mapper.xml中使用二级缓存-->
	<cache/>
  • 也可以自定义参数
	<!--在当前Mapper.xml中使用二级缓存-->
	<cache  eviction="FIFO"
			flushInterval="60000"
			size="512"
			readOnly="true"/>
  1. 测试
  • 问题:我们需要将实体类序列化!否则会报错!
caused by: java.io.NotserializableException: com.kuang.pojo.user
  • test
    @Test
    public void test(){
        //sqlSession1
        SqlSession sqlSession1 = MybatisUtils.getSqlSession();
        UserMapper mapper1 = sqlSession1.getMapper(UserMapper.class);
    
        User user1 = mapper1.queryUserById(1);
        System.out.println(user1);
        sqlSession1.close();
        
        //sqlSession2
        SqlSession sqlSession2 = MybatisUtils.getSqlSession();
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
        
        User user2 = mapper2.queryUserById(1);
        System.out.println(user2);
        System.out.println(user1==user2);
        
        sqlSession2.close();
    }
  • 小结:
    • 只要开启了二级缓存,在同一个Mapper下都有效。
    • 所有的数据优先放在一级缓存中。
    • 但是当会话被提交,或者被关闭后,就会提交至二级缓存中!

13.5 缓存原理

在这里插入图片描述

  • 用户先查二级缓存,没有再查一级缓存,再没有再查数据库,查到同时提交至一级缓存。

13.6 自定义缓存-Ehcache

  • Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存。
  • 现在多用Redis

  • 如果要在程序中使用Ehcache,先导包。
  • pom.xml
		<dependency>
			<groupId>org.mybatis.caches</groupId>
			<artifactId>mybatis-ehcache</artifactId>
			<version>1.1.0</version>
		</dependency>
  • 在mapper中指定使用我们的ehcache缓存实现!
  • UserMapper.xml
	<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  • ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
	<!--
	   diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
	   user.home – 用户主目录
	   user.dir – 用户当前工作目录
	   java.io.tmpdir – 默认临时文件路径
	 -->
	<diskStore path="./tmpdir/Tmp_EhCache"/>
	
	<defaultCache
			eternal="false"
			maxElementsInMemory="10000"
			overflowToDisk="false"
			diskPersistent="false"
			timeToIdleSeconds="1800"
			timeToLiveSeconds="259200"
			memoryStoreEvictionPolicy="LRU"/>
	
	<cache
			name="cloud_user"
			eternal="false"
			maxElementsInMemory="5000"
			overflowToDisk="false"
			diskPersistent="false"
			timeToIdleSeconds="1800"
			timeToLiveSeconds="1800"
			memoryStoreEvictionPolicy="LRU"/>
	<!--
	   defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
	 -->
	<!--
	  name:缓存名称。
	  maxElementsInMemory:缓存最大数目
	  maxElementsOnDisk:硬盘最大缓存个数。
	  eternal:对象是否永久有效,一但设置了,timeout将不起作用。
	  overflowToDisk:是否保存到磁盘,当系统宕机时
	  timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
	  timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
	  diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
	  diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
	  diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
	  memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
	  clearOnFlush:内存数量最大时是否清除。
	  memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
	  FIFO,first in first out,这个是大家最熟的,先进先出。
	  LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
	  LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
   -->

</ehcache>
  • 目前至少是Redis数据库需要做缓存。(K-V)

14. 29道练习题实战!

 
 

—————— THE END ——————
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zachsj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值