Springboot-Mybatis-进阶
数据库关系

ResultMap
ResultMap是Mybatis最强大的元素,它可以将查询到的复杂数据(比如查询到几个表中数据)映射到一个结果集当中。
一般的简单查询用ResultType即可,对于复杂的查询才需要使用ResultMap。
<resultMap id="唯一的标识" type="映射的pojo对象">
<id column="表的主键字段,或者可以为查询语句中的别名字段" property="映射pojo对象的主键属性" />
<result column="表的一个字段(可以为任意表的一个字段)" property="映射到pojo对象的一个属性(须为type定义的pojo对象中的一个属性)"/>
<association property="pojo的一个对象属性" javaType="pojo关联的pojo对象">
<id column="关联pojo对象对应表的主键字段" property="关联pojo对象的主席属性"/>
<result column="任意表的字段" property="关联pojo对象的属性"/>
</association>
<!-- 集合中的property须为oftype定义的pojo对象的属性-->
<collection property="pojo的集合属性" ofType="集合中的pojo对象">
<id column="集合中pojo对象对应的表的主键字段" property="集合中pojo对象的主键属性" />
<result column="可以为任意表的字段" property="集合中的pojo对象的属性" />
</collection>
</resultMap>
association
用于多对一的关系,即association包括只是一个对象。例如查询学生信息,一个学生只有一个老师
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Student implements Serializable {
private Integer id;
private String name;
private Teacher teacher;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Teacher implements Serializable {
private Integer id;
private String name;
}
<?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.lexiaoyao.mybatisdemo.mapper.StudentMapper">
<resultMap id="res" type="student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
<!-- 一对多采用association-->
<association property="teacher" javaType="teacher">
<result column="tid" property="id"></result>
<result column="tname" property="name"></result>
</association>
</resultMap>
<select id="listAll" resultMap="res">
SELECT s.id sid,s.`name` sname,s.t_id sid,t.`name` tname,t.`id` tid
FROM `student` s,`teacher` t
WHERE s.t_id = t.id
</select>
</mapper>
collection
是一对多的关系,ofType是集合中的范型类型,比如一个老师有多个学生
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Student implements Serializable {
private Integer id;
private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Teacher implements Serializable {
private Integer id;
private String name;
private List<Student> students;
}
@Repository
public interface TeacherMapper {
Teacher getById(@Param("id") Integer id);
}
<?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.lexiaoyao.mybatisdemo.mapper.TeacherMapper">
<resultMap id="res" type="teacher">
<result column="tname" property="name"></result>
<result column="tid" property="id"></result>
<collection property="students" ofType="student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
</collection>
</resultMap>
<select id="getById" parameterType="int" resultMap="res">
SELECT s.id sid,s.`name` sname,s.t_id sid,t.`name` tname,t.`id` tid
FROM
`student` s,`teacher` t
WHERE
s.t_id = t.id
AND
t.`id` = #{id}
</select>
</mapper>
动态sql
if
如果有字段则加入sql
<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>
</select>
where
这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个‘where’。此外,如果标签返回的内容是以AND 或OR 开头的,则它会剔除掉。
<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
set能够处理进行update操作时,set时候多余的逗号处理
<update 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};
</update>
choose
有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
note只有一个条件触发
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from blog
<where>
<choose>
<when test="title != null">
title = #{title}
</when>
<when test="author != null">
and author = #{author}
</when>
<otherwise>
and views = #{views}
</otherwise>
</choose>
</where>
</select>
foreach
一般用于集合中遍历搜索
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from blog
<where>
<!--
collection:指定输入对象中的集合属性
item:每次遍历生成的对象
open:开始遍历时的拼接字符串
close:结束时拼接的字符串
separator:遍历对象之间需要拼接的字符串
select * from blog where 1=1 and (id=1 or id=2 or id=3)
-->
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
缓存
一级缓存
mybatis的一级缓存是默认打开的,只在一个session内有效。
一级的缓存的使用价值不大,所以一般使用二级缓存
二级缓存
开启二级缓存
mybatis的二级缓存默认也是开启的,但是在使用的时候,一般手动显式开启。
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="cacheEnabled" value="true"/>
</settings>
配置
直接在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.lexiaoyao.mybatisdemo.mapper.TeacherMapper">
<cache eviction="FIFO" flushInterval="60000" size="512" type="true"></cache>
<resultMap id="res" type="teacher">
<result column="tname" property="name"></result>
<result column="tid" property="id"></result>
<collection property="students" ofType="student">
<result column="sid" property="id"></result>
<result column="sname" property="name"></result>
</collection>
</resultMap>
<select id="getById" parameterType="int" resultMap="res">
SELECT s.id sid,s.`name` sname,s.t_id sid,t.`name` tname,t.`id` tid
FROM
`student` s,`teacher` t
WHERE
s.t_id = t.id
AND
t.`id` = #{id}
</select>
</mapper>
异常
DataAccessException
DataAccessException用于处理数据处理的异常,包括插入数据时有唯一性约束导致失败等问题。
如果插入重复的主键数据,mybatis会抛出异常。
Cause: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '10' for key 'PRIMARY'
; Duplicate entry '10' for key 'PRIMARY'; nested exception is java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '10' for key 'PRIMARY'
只需要在定义接口时,抛出异常
void insertUser(User user) throws DataAccessException;
调用时候不活
@Test
void test() {
try {
User user = new User().setId(10).setAge(11).setName("11");
mapper.insertUser(user);
} catch (DataAccessException e) {
e.printStackTrace();
}
// User user = new User().setId(10).setAge(11).setName("11");
// mapper.insertUser(user);
}
git
Springboot-Mybatis-进阶的更多相关文章
- Docker+SpringBoot+Mybatis+thymeleaf的Java博客系统开源啦
个人博客 对于技术人员来说,拥有自己的个人博客应该是一件令人向往的事情,可以记录和分享自己的观点,想到这件事就觉得有意思,但是刚开始写博客的时候脑海中是没有搭建个人博客这一想法的,因为刚起步的时候连我 ...
- 第五章 springboot + mybatis(转载)
本编博客转发自:http://www.cnblogs.com/java-zhao/p/5350021.html springboot集成了springJDBC与JPA,但是没有集成mybatis,所以 ...
- 第九章 springboot + mybatis + 多数据源 (AOP实现)
在第八章 springboot + mybatis + 多数据源代码的基础上,做两点修改 1.ShopDao package com.xxx.firstboot.dao; import org.spr ...
- 第五章 springboot + mybatis
springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成.集成方式相当简单. 1.项目结构 2.pom.xml <!-- 与数 ...
- 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建
基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建 前言 最近做回后台开发,重新抓起以前学过的SSM(Spring+Sp ...
- springboot mybatis 事务管理
本文主要讲述springboot提供的声明式的事务管理机制. 一.一些概念 声明式的事务管理是基于AOP的,在springboot中可以通过@Transactional注解的方式获得支持,这种方式的优 ...
- SpringBoot+Mybatis+Freemark 最简单的例子
springboot-sample 实现最简单的 SpringBoot + Mybatis + Freemarker 网页增删改查功能,适合新接触 Java 和 SpringBoot 的同学参考 代码 ...
- springboot + mybatis 前后端分离项目的搭建 适合在学习中的大学生
人生如戏,戏子多半掉泪! 我是一名大四学生,刚进入一家软件件公司实习,虽说在大学中做过好多个实训项目,都是自己完成,没有组员的配合.但是在这一个月的实习中,我从以前别人教走到了现在的自学,成长很多. ...
- springboot+mybatis+redis实现分布式缓存
大家都知道springboot项目都是微服务部署,A服务和B服务分开部署,那么它们如何更新或者获取共有模块的缓存数据,或者给A服务做分布式集群负载,如何确保A服务的所有集群都能同步公共模块的缓存数据, ...
- Java逆向工程SpringBoot + Mybatis Generator + MySQL
Java逆向工程SpringBoot+ Mybatis Generator + MySQL Meven pop.xml文件添加引用: <dependency> <groupId> ...
随机推荐
- 使用docker安装nginx并配置端口转发
使用docker安装并运行nginx命令: docker run --name=nginx -p 80:80 -d docker.io/nginx 使用命令: docker exec -it ngin ...
- 数据结构中的树(二叉树、二叉搜索树、AVL树)
数据结构动图展示网站 树的概念 树(英语:tree)是一种抽象数据类型(ADT)或是实作这种抽象数据类型的数据结构,用来模拟具有树状结构性质的数据集合.它是由n(n>=1)个有限节点组成一个具有 ...
- 嵌入式linux下获取flash分区大小
在嵌入式系统中,由于flash存储空间有限,或者是存储数据,实现数据的循环删除,需要获取到分区的使用情况,可以通过系统下的函数statfs来获取使用情况:实现代码如下: flashInfo.cpp # ...
- Django 环境下常用的模型设计
Django 环境下常用的模型设计 用户表 继承 django.contrib.auth.model import AbstractUser AbstractUser 默认已经包含了很多字段了 id ...
- Java多线程入门及实战
基本概念: 1: 程序 2 进程 3 线程 4 进程和线程的区别 5 进程和程序的区别 Java实现多线程的方法: 1 继承Thread 2 实现Runable 3 实现callable 4 线程池的 ...
- 每日一道 LeetCode (10):搜索插入位置
每天 3 分钟,走上算法的逆袭之路. 前文合集 每日一道 LeetCode 前文合集 代码仓库 GitHub: https://github.com/meteor1993/LeetCode Gitee ...
- 2020-03-25:快排、堆排和归并都是O(nlog n)的算法,为何JDK选择快速排序?
福哥答案2020-03-26: 口诀如下:冒选插希快 堆归计桶基(冒泡,选择,插入,希尔,快速,堆,归并,计数,桶,基数)冒线 平平 稳常小选平 平平 不常小插线 平平 稳常序希线 四组 不常组快四 ...
- C#LeetCode刷题之#744-寻找比目标字母大的最小字母(Find Smallest Letter Greater Than Target)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/4001 访问. 给定一个只包含小写字母的有序数组letters 和 ...
- C#LeetCode刷题之#415-字符串相加(Add Strings)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3873 访问. 给定两个字符串形式的非负整数 num1 和num2 ...
- C#LeetCode刷题之#21-合并两个有序链表(Merge Two Sorted Lists)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3818 访问. 将两个有序链表合并为一个新的有序链表并返回.新链表 ...