数据库关系

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-进阶的更多相关文章

  1. Docker+SpringBoot+Mybatis+thymeleaf的Java博客系统开源啦

    个人博客 对于技术人员来说,拥有自己的个人博客应该是一件令人向往的事情,可以记录和分享自己的观点,想到这件事就觉得有意思,但是刚开始写博客的时候脑海中是没有搭建个人博客这一想法的,因为刚起步的时候连我 ...

  2. 第五章 springboot + mybatis(转载)

    本编博客转发自:http://www.cnblogs.com/java-zhao/p/5350021.html springboot集成了springJDBC与JPA,但是没有集成mybatis,所以 ...

  3. 第九章 springboot + mybatis + 多数据源 (AOP实现)

    在第八章 springboot + mybatis + 多数据源代码的基础上,做两点修改 1.ShopDao package com.xxx.firstboot.dao; import org.spr ...

  4. 第五章 springboot + mybatis

    springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成.集成方式相当简单. 1.项目结构 2.pom.xml <!-- 与数 ...

  5. 基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建

    基于Maven的Springboot+Mybatis+Druid+Swagger2+mybatis-generator框架环境搭建 前言 最近做回后台开发,重新抓起以前学过的SSM(Spring+Sp ...

  6. springboot mybatis 事务管理

    本文主要讲述springboot提供的声明式的事务管理机制. 一.一些概念 声明式的事务管理是基于AOP的,在springboot中可以通过@Transactional注解的方式获得支持,这种方式的优 ...

  7. SpringBoot+Mybatis+Freemark 最简单的例子

    springboot-sample 实现最简单的 SpringBoot + Mybatis + Freemarker 网页增删改查功能,适合新接触 Java 和 SpringBoot 的同学参考 代码 ...

  8. springboot + mybatis 前后端分离项目的搭建 适合在学习中的大学生

    人生如戏,戏子多半掉泪! 我是一名大四学生,刚进入一家软件件公司实习,虽说在大学中做过好多个实训项目,都是自己完成,没有组员的配合.但是在这一个月的实习中,我从以前别人教走到了现在的自学,成长很多. ...

  9. springboot+mybatis+redis实现分布式缓存

    大家都知道springboot项目都是微服务部署,A服务和B服务分开部署,那么它们如何更新或者获取共有模块的缓存数据,或者给A服务做分布式集群负载,如何确保A服务的所有集群都能同步公共模块的缓存数据, ...

  10. Java逆向工程SpringBoot + Mybatis Generator + MySQL

    Java逆向工程SpringBoot+ Mybatis Generator + MySQL Meven pop.xml文件添加引用: <dependency> <groupId> ...

随机推荐

  1. Java语言特性

    Java的语言特性: 1.语法相对简单 2.面向对象 3.分布性 4.可移植性 5.安全性 6.健壮性 7.解释性 8.多线程 9.动态性与并发性 Java中的面向对象编程: 面向对象程序设计(Obj ...

  2. 群晖系统如何通过Video Station套件管理NAS中的视频

    一.PC端观看视频 1.在NAS套件中心找到Video Station套件,安装套件 2.设置video套件别名,便于后期使用,控制面板----应用程序门户----video Station 3.选中 ...

  3. vue 项目运行报错

    'vue-cli-service' 不是内部或外部命令,也不是可运行的程序 或批处理文件. 运行Vue项目文件的时候报如下错误 需要先用淘宝镜像来运行:cnpm install 然后运行成功后 就可以 ...

  4. Java流程控制,for,switch,while.break,continue,return

    Java流程控制,for,switch,while.break,continue,return

  5. FTP服务器搭建及自动备份设置

    本次随笔内容主要是FTP服务器搭建. 其实去年十月服务器就搭建完了.当时写了个PPT保存了一下,准备以后写博客,结果时隔快一年我自己都快要看不懂我自己写的PPT了  ( = o = ) 不过还是尽量尝 ...

  6. Go 中的动态作用域变量

    这是一个 API 设计的思想实验,它从典型的 Go 单元测试惯用形式开始: func TestOpenFile(t *testing.T) { f, err := os.Open("notf ...

  7. wifi渗透

    前言 本文主要讲述 家庭家庭家庭中(重要的事情说三遍,企业认证服务器的wifi一般非常非常的安全破解不来)如何破解wifi密码,破解wifi密码后的内网渗透利用(简单说明),如何设置wifi路由器更安 ...

  8. 【JVM】JVM优化过程全记录

    请大神移步:https://segmentfault.com/a/1190000010510968?utm_source=tuicool&utm_medium=referral 今天看JVM群 ...

  9. 浅谈:C#中的非泛型集合

    1.首先:ArrayList:非泛型集合 List:泛型集合 集合跟数组比较我们更容易理解.数组:1,长度固定2,数据类型预先声明 集合:1,长度可变2,数据类型预先声明的为泛型集合,数据类型不限定为 ...

  10. 剑指Offer——II平衡二叉树

    class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # 这道题使用中序遍历加上 ...