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> ...
随机推荐
- .Net Core 3.0依赖注入替换 Autofac
今天早上,喜庆的更新VS2019,终于3.0正式版了呀~ 有小伙伴问了一句Autofac怎么接入,因为Startup.ConfigureServices不能再把返回值改成IServiceProvide ...
- SqlServer 多表连接、聚合函数、模糊查询、分组查询应用总结(回归基础)
--exists 结合 if else 以及 where 条件来使用判断是否有数据满足条件 select * from Class where Name like '%[1-3]班' if (not ...
- proxy的实现(代理)
29.proxy的实现 (代理) get方法 //定义一个对象personvar person = {"name":"张三”};//创建一个代理对象pro, 代理pers ...
- 2020 重新出发,JAVA 学习计划
------ @[toc]# 前言 我呢已经工作七年了,一直没有换工作,因为我这个人没什么太大的野心,安安稳稳的生活就挺好,目前的公司虽然福利一般,但是工作稳定,环境也都很熟悉了. 但是今年,到目前为 ...
- 丢弃掉那些BeanUtils工具类吧,MapStruct真香!!!
在前几天的文章<为什么阿里巴巴禁止使用Apache Beanutils进行属性的copy?>中,我曾经对几款属性拷贝的工具类进行了对比. 然后在评论区有些读者反馈说MapStruct才是真 ...
- Linux下安装Readis
Redis的官方下载网址是:http://redis.io/download (这里下载的是Linux版的Redis源码包) Redis服务器端的默认端口是6379. 首先我们先把整体的流程先书写下 ...
- noip复习——快速幂
\(a ^ n \bmod p\) \(a, p, n \leq 10^9\) 最普通的二进制拆分 #define LL long long LL qpow(LL a, LL n, LL p) { L ...
- Oracle用户授权
一.用户授权 1)普通权限 grant ${autoType1, autoType2, autoType3, ...} to ${userName} identified by ${password} ...
- Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.List com.catherine.forrealm.about_utils.RealmHelper.findAllStudent()' on a null object reference
报错: 解决方法: private RealmHelper realm_search = new RealmHelper(); 进而发现在写RecyclerView时,遗漏如下代码: recy_sea ...
- Flutter FlatButton 按钮基本各种用法
Flutter中给我们预先定义好了一些按钮控件给我们用,常用的按钮如下 RaisedButton :凸起的按钮,其实就是Android中的Material Design风格的Button ,继承自Ma ...