Mybatis-06 动态Sql
Mybatis-06 动态Sql
多对一处理
多个学生,对应一个老师
对于学生这边而言,关联多个学生,关联一个老师 【多对一】
对于老师而言,集合,一个老师又很多学生 【一对多】
1.创建数据库


2.创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class teacher {
private int id;
private String name;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class student {
private int id;
private String name;
private teacher teacher;
}
3.接口类
public interface StudentMapper {
public List<student> getStudent();
}
4.Mapper.xml文件
思路:
- 查询出所有学生
- 根据tid查询其对应老师
复杂的对象就用association和collection
对象:association 集合:collection
4.1 按照查询嵌套处理
<mapper namespace="com.Dao.StudentMapper">
<resultMap id="stutea" type="pojo.student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="pojo.teacher" select="getTeacher"/>
</resultMap>
<select id="getStudent" resultMap="stutea">
select * from mybatistest.stu
</select>
<select id="getTeacher" resultType="pojo.teacher">
select * from mybatistest.teacher where id = #{id}
</select>
</mapper>
4.2 按照结果嵌套处理
<mapper namespace="com.Dao.StudentMapper">
<select id="getStudent" resultMap="studentTeacher2">
select s.id,s.name,t.name
from mybatistest.stu s,mybatistest.teacher t
where s.tid=t.id
</select>
<resultMap id="studentTeacher2" type="pojo.student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" javaType="pojo.teacher">
<result property="name" column="name"/>
</association>
</resultMap>
</mapper>
5.测试
@Test
public void getStudent(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
List<student> student = mapper.getStudent();
for (pojo.student student1 : student) {
System.out.println(student1);
}
sqlSession.close();
}


一对多处理
数据库不变
1.创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class teacher {
private int id;
private String name;
private List<student> students;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class student {
private int id;
private String name;
// private teacher teacher;
private int tid;
}
2.接口类
public interface TeacherMapper {
public teacher getTeacher(@Param("tid") int id);
}
3.Mapper.xml文件
3.1 按照查询嵌套处理
<mapper namespace="com.Dao.TeacherMapper">
<select id="getTeacher" resultMap="geTeacher" >
select * from mybatistest.teacher where id = #{tid}
</select>
<resultMap id="geTeacher" type="pojo.teacher">
<collection property="students" javaType="ArrayList" ofType="pojo.student" select="getStudent" column="id"></collection>
</resultMap>
<select id="getStudent" resultType="pojo.student">
select * from mybatistest.stu where tid = #{tid}
</select>
</mapper>
3.2 按照结果嵌套处理
<mapper namespace="com.Dao.TeacherMapper">
<select id="getTeacher" resultMap="teacherStudent">
select t.id tid,t.name tname,s.id sid,s.name sname
from mybatistest.stu s,mybatistest.teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="teacherStudent" type="pojo.teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="pojo.student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
4.测试
@Test
public void getTeacher(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
teacher teacher = mapper.getTeacher(1);
System.out.println(teacher);
sqlSession.close();
}


ofType & javaType
javaType用来指定实体类中属性ofTyoe用来指定映射到List或者集合中pojo类型,泛型中的约束类型
注意点:注意一对多和多对一中,属性名和字段的问题
动态sql
动态SQL就是指根据不同的条件生成不同的SQL语句
- If
- choose (when, otherwise)
- trim (where, set)
- foreach
1.基础准备
1.1 创建数据库
CREATE TABLE `blog`(
`id` INT(10) NOT NULL COMMENT '博客id',
`title` VARCHAR(20) NOT NULL COMMENT '博客标题',
`author` VARCHAR(10) NOT NULL COMMENT '作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(20) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB CHARSET=utf8;

1.2 创建实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
1.3 创建接口类
public interface BlogMapper {
public int addBlog(Blog blog);
}
1.4 创建Mapper.xml文件
<mapper namespace="com.Dao.BlogMapper">
<insert id="addBlog" parameterType="pojo.Blog">
insert into mybatistest.blog(id,title,author,create_time,views)
values (#{id},#{title},#{author},#{createTime},#{views})
</insert>
</mapper>
1.5 测试代码
@Test
public void Test(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog(1, "title", "张", new Date(), 11);
int i = mapper.addBlog(blog);
System.out.println(i);
}
2.IF
接口
public interface BlogMapper {
public List<Blog> queryBlogIF(Map map);
}
映射文件
<mapper namespace="com.Dao.BlogMapper">
<select id="queryBlogIF" parameterType="map" resultType="pojo.Blog">
select * from mybatistest.blog where 1=1
<if test="views != null">
and views > #{views}
</if>
<if test="author != null">
and author=#{author}
</if>
<if test="title != null">
and title like #{title}
</if>
</select>
</mapper>
测试
@Test
public void queryBlogIF(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("views",10);
List<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

注意:
- 未绑定mapper
在配置文件中绑定:
<mappers>
<mapper class="com.Dao.BlogMapper"/>
</mappers>
- createTime数据为null
这是因为在实体类中,数据库中定义时间属性为:create_time,有_。
可以开启驼峰命名法映射,在配置文件中加入:
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
在数据库字段命名规范中常常用下划线 "_" 对单词进行连接,如:"create_time",而开发中实体属性通常会采用驼峰命名法命名为 createTime 。
3.choose (when, otherwise)
接口
public interface BlogMapper {
public List<Blog> queryBlogChoose(Map map);
}
映射文件
<select id="queryBlogChoose" parameterType="map" resultType="pojo.Blog">
select * from mybatistest.blog
<where>
<choose>
<when test="title != null">
and title like #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views > #{views}
</otherwise>
</choose>
</where>
</select>
测试
@Test
public void queryBlogChoose(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("title","%啦%");
List<Blog> blogs = mapper.queryBlogChoose(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

4.trim (where, set)
where元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 AND 或 OR,where 元素也会将它们去除。
<where>
<if test="views != null">
views > #{views}
</if>
<if test="author != null">
and author=#{author}
</if>
<if test="title != null">
and title like #{title}
</if>
</where>
set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。
接口
public int updateBlogSet(Map map);
映射文件
<update id="updateBlogSet" parameterType="map">
update mybatistest.blog
<set>
<if test="title != null">title=#{title},</if>
<if test="author != null">author=#{author},</if>
<if test="views != null">views=#{views},</if>
</set>
where id=#{id}
</update>
测试
@Test
public void updateBlogSet(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("id",1);
map.put("title","t-test");
map.put("author","a-test");
map.put("views",100);
int i = mapper.updateBlogSet(map);
System.out.println(i);
HashMap map1 = new HashMap();
List<Blog> blogs = mapper.queryBlogIF(map1);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

5.Foreach
接口
public List<Blog> queryBlogForeach(Map map);
映射文件
<select id="queryBlogForeach" parameterType="map">
select * from mybatistest.blog
<where>
/*此处的collection是一个list,所以map需要传入一个list来进行遍历*/
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
<if test="views != null">
and views > #{views}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>
测试
@Test
public void queryBlogForeach(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, Object> map = new HashMap<String, Object>();
List<Integer> ids = new ArrayList<Integer>();
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
}

6.Sql片段
我们可以将一些公共的部分用<sql>抽取出来,方便复用!
<sql id="id-test">
<choose>
<when test="title != null">
and title like #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views > #{views}
</otherwise>
</choose>
</sql>
<select id="queryBlogChoose" parameterType="map" resultType="pojo.Blog">
select * from mybatistest.blog
<where>
<include refid="id-test"></include>
</where>
</select>
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL的格式,去排列组合就可以了
我们可以先在Mysql中写出完整的SQL,在对应的去修改称为我们的动态SQL
缓存
1.简介
查询:连接数据库,耗资源!
一次查询的结果,给他暂存在一个可以直接取到的地方——内存:缓存
那么我们再次查询的时候就可以不用走数据库了
- 缓存【Cache】?
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存中,用户查询的时候就不用从磁盘上查询了,而从缓存中查询,提高查询效率
- 为什么使用缓存?
- 减少和数据库的交互次数,减少系统开销
- 什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据
2.Mybatis缓存
Mybatis系统中默认顶一个两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。这是sqlSession级别的,随着Session开启而开启,关闭而关闭,也称其为本地缓存
- 二级缓存是namespace级别的,需要手动开启和配置
- Mybatis有一个配置缓存的接口Cache,可以定义二级缓存
注意事项:
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
3.一级缓存
一级缓存也叫本地缓存:
- 在域数据库交互的同一个会话中,会将查过的数据放在缓存中
- 以后再查询相同的数据时,直接从缓存中取数据
测试
- 开启日志
- 测试两次查询同一条数据
@Test
public void cache(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
System.out.println("===============================");
user user1 = mapper.getUserById(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}

从图中可以看出,数据在一级缓存,只查询一次,这两者相同,为true
手动清理缓存
@Test
public void cache(){
SqlSession sqlSession = mybatis_util.getSqlSession1();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
user user = mapper.getUserById(1);
System.out.println(user);
sqlSession.clearCache(); //手动清理缓存
System.out.println("===============================");
user user1 = mapper.getUserById(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}

从图中可以看出,数据在一级缓存,手动清理缓存后,查询了两次,这两者不同,为false
4.二级缓存
二级缓存是基于namespace的缓存,它的作用域比一级大
- 我们希望当会话关闭的时候,存储在一级缓存的数据可以进入二级缓存
- 用户进行第二次会话的时候,就可以直接从二级缓存拿数据
4.1 开启缓存
在配置文件开启二级缓存
<setting name="cacheEnabled" value="true"/>
在对应的mapper.xml中选择开启二级缓存
<cache/>
也可以自定义cache
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
4.2测试
@Test
public void SecondCache(){
SqlSession sqlSession = mybatis_util.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
user user = mapper.getUserByID(1);
System.out.println(user);
sqlSession.close();
System.out.println("===============================");
SqlSession sqlSession1 = mybatis_util.getSqlSession();
UserDao mapper1 = sqlSession1.getMapper(UserDao.class);
user user1 = mapper1.getUserByID(1);
System.out.println(user1);
System.out.println(user==user1);
sqlSession.close();
}

从图中可以看出,开启二级缓存后,sqlSession关闭时,数据存入二级缓存,直接在二级缓存调出数据,只用查询了一次 ,这两者不同,为false
注意:可能会出现的错误:
Error serializing object. Cause:java.io.NotSerializableException: pojo.user,这个错误只需要在实体类继承Serializable,即:class user implements Serializable
5.缓存原理

6.自定义缓存-encache
Ehcache是一种广泛使用的开源Java分布式缓存。EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
6.1 导入依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.0</version>
</dependency>
6.2 导入配置文件
创建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 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"/>
</ehcache>
6.3 开启二级缓存
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
其实没什么大的区别,想用可以用
Mybatis-06 动态Sql的更多相关文章
- MyBatis的动态SQL详解
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...
- Mybatis解析动态sql原理分析
前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...
- mybatis 使用动态SQL
RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role ro ...
- MyBatis框架——动态SQL、缓存机制、逆向工程
MyBatis框架--动态SQL.缓存机制.逆向工程 一.Dynamic SQL 为什么需要动态SQL?有时候需要根据实际传入的参数来动态的拼接SQL语句.最常用的就是:where和if标签 1.参考 ...
- 使用Mybatis实现动态SQL(一)
使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面: *本章节适合有Mybatis基础者观看* 前置讲解 我现在写一个查询全部的 ...
- MyBatis探究-----动态SQL详解
1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不 ...
- mybatis中的.xml文件总结——mybatis的动态sql
resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...
- mybatis.5.动态SQL
1.动态SQL,解决关联sql字符串的问题,mybatis的动态sql基于OGNL表达式 if语句,在DeptMapper.xml增加如下语句; <select id="selectB ...
- MyBatis的动态SQL详解-各种标签使用
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...
- 利用MyBatis的动态SQL特性抽象统一SQL查询接口
1. SQL查询的统一抽象 MyBatis制动动态SQL的构造,利用动态SQL和自定义的参数Bean抽象,可以将绝大部分SQL查询抽象为一个统一接口,查询参数使用一个自定义bean继承Map,使用映射 ...
随机推荐
- 常见JVM面试题及答案整理
常见JVM面试题及答案整理 1.什么情况下会发生栈内存溢出 2.JVM内存模型 3.JVM内存为什么要分成新生代,老年代,持久代.新生代中为什么要分为Eden和Survivor. 3.1共享内存区划分 ...
- 自定义tree
function YpTreeMenu(ypTreeMenu,treeObj) { this.ypTreeMenu=ypTreeMenu; this.treeObj=treeObj; this.tre ...
- Dedecms织梦搜索页显示条数的更改方法
织梦dedecms搜索结果页面的显示条数默认是10条,这个数值在模板当中是不能控制的. 解决方法: 打开根目录下的plus文件夹,找到search.php修改一段代码: 在大概第15行,找到 $ pa ...
- HarmonyOS单模块编译与源码导读
我这里以3518的开发板为例进行讲解,3516的也是通用的. 下面是之前全量编译的脚本 python build.py ipcamera_hi3518ev300 -b debug HarmonyOS最 ...
- 为什么对gRPC做负载均衡会很棘手?
在过去的几年中,随着微服务的增长,gRPC在这些较小的服务之间的相互通信中获得了很大的普及,在后台,gRPC使用http/2在同一连接和双工流中复用许多请求. 使用具有结构化数据的快速,轻便的二进制协 ...
- 【noi 2.6_9289】Ant Counting 数蚂蚁{Usaco2005 Nov}(DP)
题意:有M个家族的蚂蚁,各Ni只(互相相同).问选出 l~r 只的不同方案数. 解法:很基础的一种DP,不要被"排列组合"所迷惑了啊~我之前接触过这个类型,可惜又忘了,一定要记住! ...
- Python模块——Openpyxl(EXCEL)操作
一.安装模块 pip install openpyxl 二.文件的操作 2.1文件创建 from openpyxl import Workbook #创建新的excle文件 wk = Workbook ...
- SPOJ SUBST1 New Distinct Substrings(后缀数组 本质不同子串个数)题解
题意: 问给定串有多少本质不同的子串? 思路: 子串必是某一后缀的前缀,假如是某一后缀\(sa[k]\),那么会有\(n - sa[k] + 1\)个前缀,但是其中有\(height[k]\)个和上一 ...
- Makefile 流程控制(error,warning)等调试选项
1.退出码 0 ok1 错误2 使用了-q 选项 且目标不需要更新 返回2 2.选项 -f --file 指定makefile脚本 -n --just-print --dry -run -- reco ...
- Hive Tutorial 阅读记录
Hive Tutorial 目录 Hive Tutorial 1.Concepts 1.1.What Is Hive 1.2.What Hive Is NOT 1.3.Getting Started ...