Mybatis-进阶

举报
AAAI 发表于 2021/07/04 23:53:36 2021/07/04
【摘要】 多对一* sql约束 多个学生一个年级 CREATE TABLE IF NOT EXISTS `student`( `id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号', `name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '学号', `gradeid` INT(4)...

多对一*

sql约束

在这里插入图片描述

多个学生一个年级

CREATE TABLE IF NOT EXISTS `student`(
	`id` INT(4) NOT NULL AUTO_INCREMENT COMMENT '学号', `name` VARCHAR(30) NOT NULL DEFAULT '匿名' COMMENT '学号',
	`gradeid` INT(4) NOT NULL  COMMENT '学生年级', PRIMARY KEY(`id`), KEY `FK_gradeid` (`gradeid`), #外键--grade的主键 CONSTRAINT `FK_gradeid` FOREIGN KEY (`gradeid`) REFERENCES `grade`(`gradeid`)# 约束 # KEY 约束名 (引用列)  # CONSTRAINT 约束名 FOREIGN KEY (当前引用列) REFERENCES 引用表(引用列)
)ENGINE=INNODB DEFAULT CHARSET=utf8

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

一般一对多关系都由多端来负责维护关系,在写pojo时,外键关联应该写关联的实体类。

pojo.Student.java

public class Student{ private int id; private String name; private Grade grade;  // 关联年级,年级实体类
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5

一个表对应一个pojo(JavaBean )类,一个pojo对应一个Mapper,一个Mapper对应一个xml文件

dao(mapper).StudentMapper.java

public interface StudentMapper{ }

  
 
  • 1
  • 2
  • 3

rescource.dao(mapper).StudentMapper.xml

<?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">
<mapper namespace="com.xx.dao.StudentMapper">
	<select id="getUserList" resultType="com.xxx.pojo.User"> select * from School.Student </select> </mapper>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

配置mybatis-config.xml

做项目orm映射的实体bean一般都是和结果集对应不是和表对应的。不关心你来自哪个表只关心你查出来的数据。

关联的嵌套 Select 查询

对于查询多对一关系表,查询外键学习,首先获取学生信息,通过查询的学生信息的gradeid,查询年级信息。但是由于java中年级是一个对象,因此涉及到复杂查询,通过对查询出来的学生信息进行重新赋值,使用resultMap,在查询复杂属性时,将属性和其他查询语句进行连接。获取到年级类的查询之后的信息,添加到学生查询之后的信息里面。

即:通过学生信息查出来的年级ID,再去数据库查该年级ID的信息,然后放到学生对象的属性里

复杂查询:对象:association;集合:collection

StudentMapper.xml

<select id="getStudent" resultMap="StudentGrade"> <!--子查询-->
	select * from stduent
</select>
<resultMap id="StudentGrade" type="Student"> <result property="id" column="id" />
	<result property="name" column="name"/> <association property="grade" column="gradeid" javaType="Grade" select="getGrade"> <!--gradeid被设置为对应嵌套 Select 语句的参数。--> </association>
</resultMap>

<select id="getGrade" resultMap="Grade">
	select * from grade where id = # {gradeid}
</select>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

这种方式虽然很简单,但在大型数据集或大型数据表上表现不佳。这个问题被称为“N+1 查询问题”。 概括地讲,N+1 查询问题是这样子的:

  • 你执行了一个单独的 SQL 语句来获取结果的一个列表(就是“+1”)。
  • 对列表返回的每条记录,你执行一个 select 查询语句来为每条记录加载详细信息(就是“N”)。

虽然,MyBatis 能够对这样的查询进行延迟加载,因此可以将大量语句同时运行的开销分散开来。 然而,如果你加载记录列表之后立刻就遍历列表以获取嵌套的数据,就会触发所有的延迟加载查询,性能可能会变得很糟糕。

关联的嵌套结果映射

<select id="getStudent" resultMap="StudentGrade"> <!--联表查询-->
	select s.id sid, s.name sname, g.name gname from stduent s, grade g where s.gradeid = g.id
</select>
<resultMap id="StudentGrade" type="Student"> <result property="id" column="sid" />
	<result property="name" column="sname"/> <association property="grade" javaType="Grade"> <result property="name" column="gname"/> </association>
</resultMap>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

注意:结果查询不能懒加载。

一对多

<resultMap id="blogResult" type="Blog">
  <id property="id" column="blog_id" />
  <result property="title" column="blog_title"/>
  <collection property="posts" ofType="Post"> <id property="id" column="post_id"/> <result property="subject" column="post_subject"/> <result property="body" column="post_body"/>
  </collection>
</resultMap>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

注意

javaType:指定实体类中的属性类型

ofType:指定映射到List或者集合中的pojo类型,泛型中的约束类型。

动态sql*

根据不同条件生成不同的SQL语句

小技巧

驼峰命名转换

mybatis-config.xml

<settings>
	<setting name="logImpl" value="STDOUT_LOGGING"/> <!--开启驼峰命名转换--> <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5

ID随机

IDutils.java

@SuppressWarnings("all") //抑制警告
public class IDutils{ public static Sting getId(){ return UUID.randomUUID().toString().replaceAll("-",""); } @Test public void test(){ System.out.println(IDutils.getId()); }
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

IF

<select id="BlogWithTitle" parameterType="map" resultType="Blog">
  SELECT * FROM mybatis.blog
  WHERE 1=1 <!--1=1是为了where后所有判断条件都不符时,依然可以执行查询而不报错.
1=1是为了条件中and关键字能够进行作用为拼接条件-->
  <if test="title != null"> AND title = #{title}
  </if> <if test="author != null"> AND author = #{author}
  </if>
</select>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

BlogMapper.java

public interface BlogMapper{ List<Blog> BlogWithTitle(Map map);
}

  
 
  • 1
  • 2
  • 3

后台测试:

SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();
map.put("author","xxx");
List<Blog> blogs = mapper.BlogWithTitle(map);
for (Blog blog:blogs){ System.out.println(blog);
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

choose、when、otherwise

<select id="findActiveBlogLike" resultType="Blog">
  SELECT * FROM  mybatis.blog
  <WHERE > <choose> <!--满足第一个就会返回,和switch中的break一样--> <when test="title != null"> AND title like #{title} </when> <when test="author != null and author.name != null"> AND author_name like #{author.name} </when> <otherwise> AND featured = 1 </otherwise> </choose> </WHERE>
</select>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

trim、where、set

元素只会在子元素有返回内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,*** * 元素也会将它们去除。

用于动态更新语句的类似解决方案叫做 setset 元素可以用于动态包含需要更新的列,忽略其它不更新的列。即去掉连接的最后一个逗号。

<update id="updateAuthorIfNecessary">
  update Author <set> <if test="username != null">username=#{username},</if> <!--当map.username("bio","xxx");时,bio,则自动去掉连接的最后一个逗号--> <!--当map.put("bio","xxx");时,没有更新username,则跳过这条语句--> <if test="bio != null">bio=#{bio}</if> </set>
  where id=#{id}
</update>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

trim

通过自定义 trim 元素来定制 where 元素的功能。

foreach

遍历collection,将元素拼接成一个条件串

声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。

<!--select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
select * from mybatis.blog where 1=1 and id in (1,2,3)
-->
<select id="selectPostIn" parameterType="map" resultType="domain.blog.Post">
  SELECT * from mybatis.blog
<where> <!--传递map集合--> <!--sql语句不区分空格-->
  <foreach item="id"  collection="list" open="and (" separator="or" close=")"> id = #{id}
  </foreach>
</where>
</select>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap();

ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
map.put("list",list);
List<Blog> blogs = mapper.BlogWithTitle(map);
for (Blog blog:blogs){ System.out.println(blog);
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

总结

动态SQL本质还是SQL,只是再SQL层面,执行一个逻辑代码。

动态SQL就是不同的条件生成不同的语句,拼接SQL语句

SQL片段

<sql id="username-bio">
	<if test="username != null">username=#{username},</if> <if test="bio != null">bio=#{bio}</if>
</sql>
<!--将一些复用的语句进行封装,提高复用性-->
<select id="Author">
  select * from blog <where> <include refid="username-bio"></include> </where>
</update>

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

使用SQL标签抽取公共部分,使用include进行引用。

最好基于单表来定义SQL片段,不要存在where标签。

缓存 5.11

读写分离,主从复制

减少和数据库交互次数,减少系统开销。

一级缓存

默认,SqlSession级别的缓存,称为本地缓存,只在一次SqlSession有效,源码里就是一个Map。

与数据库同一次会话期间查询的数据会放在本地缓存中,之后获取相同的数据之间从缓存中取。

开启日志

<settings>
	<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

  
 
  • 1
  • 2
  • 3

缓存失效:

1.查询不同的东西
2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存
3.查询不同的Mapper.xml
4.手动清理缓存

sqlSession.clearCache(); // 手动清除缓存

  
 
  • 1

二级缓存

手动开启,namespace级别的缓存。二级缓存也叫全局缓存

SQL 映射文件中添加一行:

<cache/>

  
 
  • 1

二级缓存是跨SqlSession的。基于namespace级别的缓存。

namespace

  • Liunx:这个namespace里面,用户是具有root权限的。
  • 在关系数据库系统中,命名空间namespace指的是一个表的逻辑分组,同一组中的表有类似的用途。
  • K8S:资源隔离+权限控制

,一个名称空间,对应一个二级缓存;

工作机制

  • 一个会话查询一条数据,这个数据就会被放在当前会话的一-级缓存中;

  • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;

  • 新的会话查询信息,就可以从二级缓存中获取内容;

  • 不同的mapper查出的数据会放在自己对应的缓存(map)中;

FIFO缓存:先进先出策略

可用的清除策略有:

  • LRU – 最近最少使用:移除最长时间不被使用的对象。
  • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
  • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
  • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
<!--显示开启的全局缓存-->
<setting name="cacheEnable" value="true"/>

  
 
  • 1
  • 2
<!--在当前Mapper. xmL中使用二级缓存-->
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
<!--readOnly为True时是读相同实例,false时是读拷贝值,相对安全,所以会出现比较时出现false-->

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

技巧

<select id="queryUserById" resultType="user" useCache="false"> <!--更新比较频繁,关闭缓存--> select * from user where id = #{id}
</select>
<update id="updateUser" parameterType="user" flushCache="false"> <!--更新时,不刷新缓存--> update mybatis .user set name=#{ name}, pwd=#{pwd} where id = #{id};
</update>
</mapper>


  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

注意:

我们需要将实体类序列化!否则就会报错!
Caused by: java. io. NotSerializableException: com. kuang. pojo.user

序列化是因为实体在二级缓存中,所以需要序列化的处理才能方便查找。

将对象转为字节流存储到硬盘上,当JVM停机的话,字节流还会在硬盘上默默等待,等待下一次JVM的启动,把序列化的对象,通过反序列化为原来的对象,并且序列化的二进制序列能够减少存储空间(永久性保存对象)。

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable { private int id; private String name; private String pwd;
}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

小结:

  • 只要开启了二级缓存,在同一个Mapper下就有效
  • 所有的数据都会先放在一-级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓冲中!

原理

用户→二级缓存→一级缓存→数据库

二级缓存作用域:一个mapper.xml文件,就是namespace作用域

在这里插入图片描述

自定义缓存-ehcache

java分布式缓存,面向通用缓存

文章来源: blog.csdn.net,作者:αβγθ,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/weixin_38022166/article/details/118463635

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。