学习地址:狂神说Mybatis
写于07/12/2021
环境:
- JDK1.8
- MySQL 5.7
- maven 3.6.1
- IDEA
回顾:
- JDBC
- MySQL
- Java基础
- Maven
- Junit
框架:配置文件。学习最好的方式:看官网文档
1.简介
1.1 什么是mybatis
- MyBatis 是一款优秀的持久层框架
- 它支持自定义 SQL、存储过程以及高级映射
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
如何获得mybatis
- github
- maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
1.2 持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据持久化方法:数据库(jdbc),io文件持久化
- 生活中:冷藏可以让物体持久,罐头
为什么需要数据持久化?
- 有些对象不能丢掉:存在银行的钱不能没
- 内存成本高
1.3 持久层
Dao层,service层,controller层
- 完成持久化工作代码的代码块
- 层界限十分明显
1.4 为什么需要mybatis
- 帮助程序员将数据存入数据库
- 方便
- 传统的jdbc代码太复杂了,简化语句利用框架
- 不用mybatis也可以。更容易上手。技术没有高低之分
- 优点
最重要的一点:使用的人多
spring springmvc springboot
2. 第一个Mybatis程序
思路
- 搭建环境
- 导入mybatis
- 编写代码
- 测试
2.1 搭建环境
数据库
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT not null primary key,
`name` varchar(30) DEFAULT null,
`pwd` varchar(30) default null
)engine = innodb default charset=utf8;
insert into `user`(`id`,`name`,`pwd`)values
(1,'kuangshen1','123456'),
(2,'kuangshen2','123456'),
(3,'kuangshen3','123456')
新建项目
- 新建一个普通maven项目
- 删除src目录
2.2 创建一个模块
- 编写mybatis核心配置文件
<?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">
<!--核心配置文件-->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写工具类
package com.xu.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//SqlSessionFactory-sqlsession
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
InputStream inputStream = null;
try {
String resource = "mybatis-config.xml";
inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例
//SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.3 编写代码
- 实体类
- 接口
public interface UserDao {
List<User> getUserList();
}
- 接口实现类由原来的impl转换为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.xu.dao.UserDao">
<select id="getUserList" resultType="com.xu.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.4 测试
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.xu.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么
核心配置文件中注册mappers
可能遇到的问题:
- 配置文件没有注册
- 绑定接口错误
- 方法名不对
- 返回类型不对
- Maven导出资源问题,加入以下代码:
<!--在build中配置resuorces,来防止我们的资源导出失败-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
测试时出现的问题:
在实体类中没有重写tostring方法,导致测试时只输出结果的内存地址,重写tostring方法后解决问题
测试代码
package com.xu.dao;
import com.xu.pojo.User;
import com.xu.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserDaoTest {
@Test
public void test(){
//获得sqlsession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
// /执行sql
UserDao userdao = sqlSession.getMapper(UserDao.class);
List<User> userList = userdao.getUserList();
//方式二
// List<User> userList1 = sqlSession.selectList("com.xu.dao.UserDao.getUserList");
for (User user : userList) {
System.out.println(user.toString());
}
sqlSession.close();
}
}
测试结果
步骤:
0.导入依赖
1.MybatisUtils
2.mybatis-config.xml
3.pojo实体类
4.接口
5.dao-Mapper.xml
6.maven
7.junit测试
3. CRUD
1. namespace
namespace中的包名要和dao/mapper中名要一致
2. select
选择,查询语句
- id:对应namespace中的方法名
- resultType:sql执行语句的返回值
- parameterType
步骤
- 编写接口
//根据id查询用户
User getUserById(int id);
- 编写mapping中的sql语句
<select id="getUserById" parameterType="int" resultType="com.xu.pojo.User">
select * from mybatis.user where id = #{id}
</select>
- 测试
3. insert
4. update
5. delete
6.分析错误
- 标签不要匹配错
- resource要绑定mapper用的方式
- 程序配置需要符合逻辑规范
- 空指针主要是没有找到xml没有找到另一个xml
- 输出的xml文件存在中文乱码
- maven资源没有导出需要在pom.xml里写引入
4. 万能map
假设实体类/数据库中的字段/参数过多,我们应当考虑使用map
举例
接口
//万能map
int addUser2(Map<String,Object>map);
xml中sql语句
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id, name, pwd) values(#{userid},#{username},#{userpwd});
</insert>
测试类
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
Map<String, Object> map = new HashMap<String, Object>();
map.put("userid",5);
sqlSession.close();
}
Map传递参数,直接取key即可 【parameterType=“map”】
对象传递参数,直接取sql中对象的属性 【parameterType=“Object”】
只有一个基本类型参数的情况下,可以直接在sql中取到
多个参数用map,或者注解
思考题:模糊查询怎么写
- java代码执行时,传递通配符%%
- 在sql拼接中使用通配符
5. 配置解析
其中所有关键字的配置都要按照顺序写
1. 核心配置文件
- mybatis-config.xml
- MyBatis配置文件会深深影响MyBatis行为的设置和属性信息
2. 环境配置(enviroments)
mybatis可以配置成适应多种环境
每次只能选择一个环境
学会配套多种环境
mybatis默认的事务管理器就是JDBC,连接池:pooled
3. 属性(properties)(常用)
我们可以通过properties属性来实现引用配置文件
【通过db.properties】
编写一个配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
username=root
password=root
- 可以直接将配置全写在配置文件中
- 也可以通过键值对增加属性配置
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
</properties>
- 如果在xml与properties中都存在同一个字段,优先使用外部配置文件中字段
问题:
通过配置文件启动测试类会出现Public Key Retrieval is not allowed
最简单的解决方法是在配置文件中url后面添加 &allowPublicKeyRetrieval=true
在一切恢复后重新导入配置文件问题不会复现?
目前不会复现
4. 类型别名(typeAliases)(常用)
- 类型别名可为 Java 类型设置一个缩写名字
- 减少代码冗余
类型一
<typeAliases>
<typeAlias type="com.xu.pojo.User" alias="User"/>
</typeAliases>
手动指定实体类的名字并给外号
类型二
<typeAliases>
<package name="com.xu.pojo"/>
</typeAliases>
通过指定实体类的包,直接扫描实体类,默认的包名可以为实体类首字母小写
在实体类较多的时候建议用第二种方式,在实体类较少时可以使用第一种diy
第二种也可以diy,需要在实体类的上方加上注解
5. 设置
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
6. 其他配置
7. 映射器(mappers)
MapperRegistry:注册绑定我们的mapper文件
方式一:通过路径绑定
<mappers>
<mapper resource="com/xu/dao/UserMapper.xml"/>
</mappers>
方法二:通过class文件绑定注册
<mappers>
<mapper class="com.xu.dao.UserMapper"/>
</mappers>
注意点:
- 接口和他的mapper配置文件必须同名
- 接口和他的mapper配置文件必须在一个包里
方法三:使用包扫描进行注入绑定
<mappers>
<package name="com.xu.dao"/>
</mappers>
注意点:
- 接口和他的mapper配置文件必须同名
- 接口和他的mapper配置文件必须在一个包里
8. 生命周期
生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题
SqlSessionFactoryBuilder:
- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory:
- 可以认为为数据库连接池
- 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 最佳作用域是应用作用域
SqlSession:
- 连接到连接池的请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
- 用完之后就关闭,否则资源被占用
这里的每个mapper就代表每个具体的业务
6. 解决属性名和字段名不一致的问题
1. 问题
数据库中的字段
新建一个项目测试实体类,字段稍作修改
测试出现问题
解决方案:
- 起别名
<select id="getUserById" parameterType="int" resultType="com.xu.pojo.User">
select id,name,pwd as password from mybatis.user where id = #{id}
</select>
2. resultmap
结果集映射
id name pwd
⬇ ⬇ ⬇
id name password
<resultMap id="UserMap" type="User">
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<select id="getUserById" resultMap="UserMap">
select * from mybatis.user where id = #{id}
</select>
思路:当实体类与数据库每列名不同时,可以通过resultmap进行重新映射绑定,不需要修改数据库语句
- ResultMap的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。
- ResultMap最优秀的地方在于,虽然你已经对它相当了解了,但是根本就不需要显式地用到他们。
- 如果世界总是这么简单就好了。
7. 日志
7.1 日志工厂
如果数据库操作出现异常,我们需要排错,日志就是最好的助手
曾经:syso,debug
现在:日志工厂
- SLF4J
- LOG4J【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING【掌握】
- NO_LOGGING
在mybatis中,具体使用哪个日志,在设置中设定
STDOUT_LOGGING标准化输出
在mybatis-config.xml中配置启动日志
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
日志启动结果
7.2 Log4J
什么是log4j
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
- 先导入log4j的包
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
- log4j.properties
log4j.rootLogger=DEBUG,console,file
#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
- 配置log4j为日志的实现
<settings>
<!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
<setting name="logImpl" value="LOG4J"/>
</settings>
- log4j的使用,直接跑刚刚的测试
简单使用
- 在要使用log4j的类中导入包 import org.apache.ibatis.session.SqlSession;
- 日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
- 日志级别
logger.info("info:log4j方法");
logger.debug("进入debug方法");
logger.error("error");
8. 分页
思考:为什么分页
- 减少数据处理量
1. 使用limit分页
语法:select * from user limit startindex,pagesize
select * from user limit 3
使用mybatis实现分页,核心SQL
- 接口
List<User> getUserByLimit(Map<String,Integer>map);
- mapper xml
<select id="getUserByLimit" parameterType="map" resultMap="UserMap">
select * from mybatis.user limit #{startindex},#{pagesize}
</select>
- 测试
public void getUserByLimit(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("startindex",1);
map.put("pagesize",2);
List<User> userlist = mapper.getUserByLimit(map);
for (User user : userlist) {
System.out.println(user);
}
sqlSession.close();
}
8.2 rowbounds分页
不再使用sql分页
- 接口
List<User> getUserByRowBounds();
- mapper.xml
<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>
- 测试
public void getUserByRowBounds(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
//rowbounds实现
RowBounds rowBounds = new RowBounds(1,2);
//通过java代码层面分页
List<User> userList = sqlSession.selectList("com.xu.dao.UserMapper.getUserByRowBounds",null,rowBounds);
for (User user : userList) {
System.out.println(user);
}
sqlSession.close();
}
8.3 分页插件
了解即可
9. 使用注解开发
9.1 面向接口编程
真正的开发中,都是面向接口编程
根本原因:解耦
9.2 使用注解开发
- 注解在接口上实现
@Select("select * from user")
List<User> getUsers();
- 需要在核心配置文件中绑定接口
<mappers>
<mapper class="com.xu.dao.UserMapper"/>
</mappers>
- 测试
本质:反射机制实现
底层:动态代理
Mybatis详细执行流程
如何探究/学习方法:debug看一步一步的流程
9.3 CRUD(注解完成)
我们可以在工具中自动提交事务
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
编写接口,增加注解
public interface UserMapper {
@Select("select * from user")
List<User> getUsers();
//方法存在多个参数,所在参数必须加上@param注解
@Select("select * from user where id=#{id}")
User getUserByID(@Param("id") int id);
@Insert("insert into user(id,name,pwd) values(#{id},#{name},#{password})")
int addUser(User user);
@Update("update user set name=#{name},pwd=#{password} where id=#{id}")
int updateUser(User user);
@Delete("delete from user where id=#{id}")
int delUser(@Param("id") int id);
}
测试类
【注意:我们必须要把mapper绑定到核心配置文件里】
8.4 关于@param注解
- 方法存在多个参数(原生参数如string,如果是User这种定义对象的参数则不需要)
- 如果只有一个基本类型,可以忽略,最好也加上
- 所在参数必须加上@param注解,注解如果不与原参数同名,则在调用接口查询时也应同时更改
- 我们在SQL中引用的就是我们这里的@Param设定的属性名⬇
#{}与${}区别
- 尽量用#{},可以比较有效的防止sql注入
9. lombok
使用步骤
- idea装插件
- maven仓库
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
- 在实体类上加注解
@Data
@AllArgsConstructor
@NoArgsConstructor
支持的种类
@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var
experimental @var
@UtilityClass
Lombok config system
常用:
@Data:无参构造,get,set,tostring,hashcode,eqals
@AllArgsConstructor:有参构造
@NoArgsConstructor
10. 多对一处理
多对一
- 多个学生,对应一个老师
- 对于学生而言,关联,多个学生关联一个老师
- 对于老师而言,集合,一个老师有很多学生
SQL:
外键架构
create table `teacher`(
`id` int(10) not null,
`name` varchar(30) default null,
primary key(`id`)
)engine=INNODB default charset=utf8
insert into teacher(`id`,`name`) values(1,'TeacherQ');
create table `student`(
`id` int(10) not null,
`name` varchar(30) default null,
`tid` int(10) default null,
primary key(`id`),
key `fktid`(`tid`),
constraint `fktid` foreign key (`tid`) references `teacher`(`id`)
)engine=INNODB default charset=utf8
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1);
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);
测试环境搭建
- 导入lombok
- 新建实体类 Teacher,Student
- 建立mapper接口
- 建立mapper.xml文件
- 在核心配置文件绑定我们的mapper接口/文件【方式很多】
- 测试查询能否成功
错误解决
IDEA JUnit Test报错:3 字节的 UTF-8 序列的字节 2 无效
解决办法:
在总maven pom.xml中加入如下统一设置编码为UTF-8
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
10.1 按照查询嵌套处理
<!--思路:查学生信息
根据查出来学生信息里老师的id查老师信息 子查询
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<!--复杂的属性,我们需要单独处理
对象用association
集合用collection-->
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
回顾MySQL多对一查询方式
- 子查询
- 联表查询
11. 一对多
比如:一个老师拥有多个学生
对于老师而言,就是一对多的关系
- 环境搭建,和刚才一样
实体类
学生
@Data
public class Student {
private int id;
private String name;
private int tid;
}
老师
@Data
public class Teacher {
private int id;
private String name;
//一个老师拥有多个学生
private List<Student> students;
}
按结果嵌套处理
<!--按结果嵌套查询-->
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id and t.id=#{tid}
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<!--复杂的属性,我们需要单独处理
对象用association
集合用collection
javaType=""指定属性的类型
集合中的泛型信息,我们用ofType获取-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按查询嵌套处理
<!--子查询方式-->
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{tid}
</select>
小结
- 关联→association 【多对一】
- 集合→collection 【一对多】
- javaType & ofType
- javaType用来指定实体类中属性的类型 例如:List
- ofType用来指定映射到List或者集合当中的pojo类型,泛型中的约束类型 例如自定义的Student
注意点
- 保证SQL语句的可读性,尽量保证通俗易懂
- 注意一对多多对一中属性名字段的问题
- 如果不好排查错误,可以使用日志,建议使用log4j
- 尤其是resultmap/resulttype里的拼写一致和正确
慢查询 1s 1000s
面试必问
- MySQL引擎
- InnoDB底层原理
mysql存储引擎InnoDB详解,从底层看清InnoDB数据结构
- 索引
- 索引优化
12. 动态SQL
什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句
利用动态 SQL,可以彻底摆脱这种痛苦
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
搭建环境
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT 博客id,
`title` VARCHAR(100) NOT NULL COMMENT 博客标题,
`author` VARCHAR(30) NOT NULL COMMENT 博客作者,
`create_time` DATETIME NOT NULL COMMENT 创建时间,
`views` INT(30) NOT NULL COMMENT 浏览量
)ENGINE=INNODB DEFAULT CHARSET=utf8
创建一个基础工程
- 导包
- 编写配置文件
- 编写实体类
@Data
public class Blog {
private String id;
private String title;
private String author;
private Date createTime;
private int views;
}
- 编写实体类对应的mapper接口以及mapper.xml
有时候出现bug因为xml没有定位到实体类
IF
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</select>
choose (when, otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<choose>
<when test="title !=null">
title=#{title}
</when>
<when test="author !=null">
author=#{author}
</when>
<otherwise>
and views=#{views}
</otherwise>
</choose>
</where>
</select>
trim (where, set)
where
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</where>
</select>
set
<update id="updateBlog" parameterType="map" >
update mybatis.blog
<set>
<if test="title !=null">
title=#{title},
</if>
<if test="author !=null">
author=#{author},
</if>
</set>
where id=#{id}
</update>
所谓动态SQL,本质上还是SQL语句,只是我们可以在SQL层面去执行一个逻辑代码
SQL片段
有时候我们可以将代码中重复的片段取出来以实现复用
- 使用SQL标签抽取公共部分
<sql id="if-title-author">
<if test="title != null">
and title=#{title}
</if>
<if test="author != null">
and author=#{author}
</if>
</sql>
- 在需要使用的地方使用include标签引用
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<include refid="if-title-author"/>
</where>
</select>
注意事项:
- 最好基于单表定义SQL片段
- 不要存在where标签
foreach
<!--select * from mybatis.blog where 1=1 and (id=1 or id=2 or id=3)
我们现在传递一个万能map,这个map可以存在一个集合-->
<select id="queryBlogForeach" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<foreach collection="ids" item="id" open="and (" close=")" separator="or">
id=#{id}
</foreach>
</where>
</select>
动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,根据SQL的格式,去排列组合就可以了
建议:
- 先在MySQL写出完整的SQL语句再对应的写出动态SQL实现复用
13. 缓存
13.1 简介
查询:需要连接数据库,耗费资源
一次查询的结果会暂存在一个可以直接取到的地方-->内存:缓存
再次查询相同数据时,会直接从缓存中取到结果,不需要再走数据库
- 什么是缓存?
- 存在内存中的临时数据。
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,从缓存中查询,从而提高查询效率。解决了高并发系统的性能问题。
- 为什么使用缓存?
- 减少和数据库交互的次数,减少系统开销,提高系统效率
- 什么样的数据能使用缓存?
- 经常查询但不经常改变的数据【可以使用缓存】
13.2 Mybatis缓存
- MyBatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升查询效率
- MyBatis系统中默认定义了两级缓存:一级缓存和二级缓存
- 默认情况下,只有一级缓存开启。(SqlSession级别的缓存!也成为本地缓存)
- 二级缓存需要手动开启和配置,它是基于namespace级别的缓存
- 为了提高扩展性,MyBatis定义了缓存接口Cache。我们可以通过实现Cache接口来定义二级缓存
13.3 一级缓存
- —级缓存也叫本地缓存
- 与数据库同一次会话期间查询到的数据会放在本地缓存中
- 以后如果需要获取相同的数据,直接从缓存中拿,没必须再去查询数据库
测试步骤:
- 开启日志
- 在一个Session中查询两次相同的记录
- 查看日志输出
我们可以看到查询只进行了一次
缓存失效的情况:
- 查询不同的记录
-
进行增/删/改操作的时候,可能会改变数据,就会刷新缓存
-
查询不同的mapper
-
手动清除
小结:一级缓存默认是开启的,只在一次Sqlsession中有效,也就是拿到连接到关闭这个区间段
一级缓存就是一个map
13.4 二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存。
工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中。
- 如果当前会话关闭了,这会话对应的一级缓存就没了,但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中。
- 新的会话查询信息,就可以从二级缓存中获取内
- 不同的mapper查出的数据会放在自己对应的缓存(map)中
步骤:
- 开启全局缓存(在配置文件中
<setting name="cacheEnabled" value="true"/>
- 在要使用二级缓存的mapper中开启
<!--在当前xml中开启二级缓存-->
<cache/>
也可以自定义参数
<!--在当前xml中开启二级缓存-->
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
-
测试
-
问题:我们需要将实体类序列化,否则会报错
小结:
- 只要开启了二级缓存,在同一个mapper下就有效
- 所有数据都会先缓存在一级缓存中
- 只有当会话提交/关闭的时候,才会交到二级缓冲中
13.5 缓存原理
13.6 Ehcache缓存
Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存
要在程序中使用ehcache,先要导包
<!--mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
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>
在mapper中指定使用ehcache缓存实现
<!--在当前xml中开启二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
redis数据库做缓存 K-V