在使用maven导入依赖的时候,注意看看这个项目中 依赖到底导入了吗
maven的约定大配置记得在pom文件中导入
<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>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
1.简介
MyBatis 是一款优秀的持久层框架
它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
如何获得Mybatis
maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
1.0 持久化
数据持久化
持久化就是将程序的数据在持久状态和顺势状态转化的过程
内存:断电即失
数据库(jdbc)io文件持久化
为什么需要持久化?
有一些对象不能丢掉!
内存太贵了
1.2持久层
Dao层,Service层,Controller层
层是界限十分明显的
1.3为什么需要学习Mybatis?
传统的JDBC代码太复杂了,简化,框架
不用Mybatis也可以,技术没有高低之分
使用的人多!!
2.第一个Mybatis程序
搭建环境–>导入Mybatis–>编写代码—>测试
1.新建一个普通的maven项目
2.删除src目录
3…创建数据库s
create database `mybatis`;
use `mybatis`;
create table `user`(
`id` int(20) 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,'一丁','1234'),
(2,'雪倩','123132');
4.导入maven依赖
2.2创建一个Mabatis核心xml文件
注意这里的 resource 绑定的是实现接口的xml文件
<mappers>
<mapper resource="com/sydgm/dao/UserMapper.xml"/>
</mappers>
XML 配置文件中包含了对 MyBatis 系统的核心设置,
包括获取数据库连接实例的数据源(DataSource)
以及决定事务作用域和控制方式的事务管理器(TransactionManager)。
后面会再探讨 XML 配置文件的详细内容,这里先给出一个简单的示例:
第一步:
<?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核心配置文件-->
<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="dd123"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/sydgm/dao/UserMapper.xml"/>
</mappers>
</configuration>
第二步:
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//使用Mybatis第一步获取SqlSessionFactory对象
String resources = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resources);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//有了sqlSessionFactory,顾名思义 就可以从工厂中获取SqlSession的实例了
//sqlSession完全包含了面向数据库执行的所有方法
public static SqlSession getSqlSession() {
return sqlSessionFactory.openSession();
}
}
编写代码
实体类
package com.sydgm.pojo;
public class User {
private Integer id;
private String name;
private String pwd;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User() {
}
public User(Integer id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
Dao接口(dao包)
public interface UserDao {
List<User> getList();
}
接口实现类(dao包)目标类(工厂)
<?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">
<!--namespace="绑定一个对应的Mapper接口 指的就是UserDao"-->
<mapper namespace="com.sydgm.dao.UserDao">
<!--目标类(工厂) 实现接口-->
<!--实现getList方法 返回的结果是User类型-->
<select id="getList" resultType="com.sydgm.pojo.User">
select * from mybatis.user
</select>
</mapper>
测试
junit测试
@Test
public void getSessiontest() {
//获取sqlSession对象 SqlSession对象包含了面向数据执行的所有方法
SqlSession sqlSession = MybatisUtils.getSqlSession();
//执行sql方式一 : getMapper
//Mapper -- 映射器
//这里getMapper实际上是一种获取UserDao接口子类的映射
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getList();
//遍历结果集
for (User user : userList) {
System.out.println(user);
}
//关闭SqlSession
sqlSession.close();
}
总结第一章节
3.crud
在UserMapper.xml文件中
1.namespace 中的包名要和Mapper接口的表明一致,可以理解成实现类
select 查询
1.查询语句
·id:就是对应的namespace中的方法名 ps namespace就是这个接口时间的类
·resultType:sql语句的返回值
·parameterType:参数类型
编写接口:
// 获取全部用户
List<User> getList();
编写对应的mapper中的sql语句(实现接口):
<select id="getList" resultType="com.javasydgm.pojo.User">
select * from mybatis.user;
</select>
insert
编写接口
int insertUser(User user);
UserMapper.xml
<mapper namespace="com.sdystart.dao.UserMapper">
<Insert id="insertUser">
insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{pwd});
</Insert>
</mapper>
增删改需要提交事务
update
编写接口
int updateUser(Map map);
实现.xml文件
<Update id="updateUser" parameterType="map">
update mybatis.user set name=#{mapName} , pwd =#{mapPwd} where id =#{id}
</Update>
增删改需要提交事务
万能的Map:
假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map
接口:
// 万能的Map
int addUserMap(Map<String,Object> hashmap);
UserMapper.xml文件
<insert id="addUserMap" parameterType="map">
insert into mybatis.user(id,name,pwd) values(#{mapId},#{mapName},#{mapPwd});
</insert>
Test测试类
@Test
public void addUserMap(){
SqlSession session = MybatisUtils.getSqlSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
Map hashmap = new HashMap<String,Object>();
hashmap.put("mapId",3);
hashmap.put("mapName","小雪");
hashmap.put("mapPwd","平顶山");
userMapper.addUserMap(hashmap);
// 提交事务
session.commit();
session.close();
Map传递参数,直接在sql中取出key即可
对象传递参数,直接在sql中取对象的属性即可
只有一个基本数据类型的情况下,可以直接在sql中取到
多个参数用Map,或者注解
模糊查询:
1.java代码执行的时候,传递通配符% %
List<User> userList = userMapper.selectUserLike("%申%");
-
在sql拼接中使用通配符!
-
<!--模糊查询--> <select id="selectUserLike" parameterType="map" resultType="com.sydgm.pojo.User"> select * from mybatis.user where NAME LIKE "%"#{nameMap}"%"; </select>
4.配置环境
1.核心配置文件
mybatis-cofig.xml
MyBatis 的配置文件包含了会深深影响 MyBatis 行为的设置和属性信息
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
2.环境配置(environments)
MyBatis 可以配置成多种
不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境
Mybatis默认的事务管理器就是JDBC
连接池:POOLED
default 默认的环境选择ID是development的环境
<environments default="development">
<environment id="development">
默认事务管理器就是JDBC
<transactionManager type="JDBC">
<property name="..." value="..."/>
</transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
3.属性(properties)
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&charaterEncoding=UTF-8
username=root
password=dd123
注意properties的位置
在核心配置文件中映入
<!--引入外部配置文件-->
<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="111111"/>
</properties>
三个注意点
可以直接引入外部文件
可以在其中增加一些属性配置
如果两个文件中有同一个字段,优先使用外部的配置文件
4.类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<!--可以给实体类起一个别名-->
<typeAliases>
<typeAlias type="com.sydstart.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
<typeAliases>
<package name="com.sydstart.pojo"/>
</typeAliases>
扫描实体类的包,他的默认别名就是这个类的首字母,首字母小写!
在实体类比较少的时候,使用第一种方式
如果实体类较多,建议使用第二种
第一种可以DIY 第二种不行,如果非要改,需要在实体类上增加注解
import org.apache.ibatis.type.Alias;
@Alias("user")
public class User {}
5.设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LJWf1Vse-1633973680591)(C:\Users\申一丁\AppData\Roaming\Typora\typora-user-images\image-20210926110027945.png)]
6.其他配置
7.映射器(mappers)
方式一:【推荐使用】
<!-- 使用相对于类路径的资源引用 -->
<mappers>
<mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
<mapper resource="org/mybatis/builder/BlogMapper.xml"/>
<mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
注意:
这种方式下 .xml文件中实现接口方法
方式二:
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
<mapper class="org.mybatis.builder.AuthorMapper"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
注意点:
·接口和他的Mapper配置文件必须同名
·接口和它的Mapper配置文件必须在同一个包下
这种方式下 在接口中使用注解开发
方式三:扫描包进行注册
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
<package name="org.mybatis.builder"/>
</mappers>
注意点:
·接口和他的Mapper配置文件必须同名
·接口和它的Mapper配置文件必须在同一个包下
8.生命周期和作用域
生命周期和作用域是至关重要的
SqlSessionFactoryBuilder
一旦创建了SqlSessionFactory,就不再需要他了
局部变量
SqlSessionFactory:
说白了就是数据库连接池
SqlSessionFactory一旦被创建就应该在应用的运行期间一直存在,没有任何一个理由丢弃
或 重新创将另一个实例
最简单的就是使用单例模式或者静态单例模式
SqlSession:
连接到连接池的一个请求!
用完之后需要关闭,否则资源被占用
这里的每一个Mapper,就代表一个具体的业务
5.解决属性名和字段名不一致的问题
当pojo下的User类修改字段后:
<select id="getSelectById" resultType="User">
select * from mybatis.user where id = #{id};
//类处理器
select id , name , pwd from mybatis.user where id = #{id};
</select>
解决方案:
方案一:起别名
<select id="getSelectById" resultType="User">
select id , name , pwd as password from mybatis.user where id = #{id};
</select>
方案二:ResultMap
结果集映射
id name pwd 数据库中的字段
id name password User.class文件中的字段
<!--结果集映射-->
<resultMap id="UserMapper" type="User">
<!--column数据库中的字段,property实体类中的属性-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
<!--绑定结果集-->
<select id="getSelectById" resultMap="UserMapper">
select * from mybatis.user where id = #{id};
</select>
resultMap
元素是 MyBatis 中最重要最强大的元素
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了
如果这个世界总是这么简单就好了
6.日志
6.1日志工厂
如果一个数据库操作,出现了异常,我们需要排错,日志就是最好的帮手
SLF4J
LOG4J 【掌握】
LOG4J2
JDK_LOGGING
COMMONS_LOGGING
STDOUT_LOGGING 【掌握】
NO_LOGGING
在Mabtis中具体使用哪一个日志实现,在设置中定义
标准的日志工厂实现
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
6.2 什么是LOG4J
1.Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件
2.我们也可以控制每一条日志的输出格式
3.通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
4.这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
1.先导入LOG4J的依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.log4j.properties
#控制台输出的相关设置
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/ding.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
3.配置log4j为日志的实现
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
简单的使用:
1.在要使用的Log4j的类中,导入包
static Logger logger = Logger.getLogger(UserMapperTest.class);
2.日志级别
logger.info("info:进入了test");
logger.debug("debug:进入了test");
7.分页
使用limit分页:
接口
// 分页
List<User> getUserByLimit(Map<String,Integer> map);
.xml文件
<select id="getUserByLimit" parameterType="map" resultType="User">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>
测试
// 分页
@Test
public void getSelectLimit(){
SqlSession session = MybatisUtils.getSqlSession();
UserMapper user = session.getMapper(UserMapper.class);
Map hashMap = new HashMap();
hashMap.put("startIndex",2);
hashMap.put("pageSize",3);
List<User> listUser = user.getUserByLimit(hashMap);
for (User user1 : listUser) {
System.out.println(user1);
}
session.close();
7.2RowBounds
基本不再使用
8.使用注解开发
注解在接口上实现
@Select("select * from mybatis.user ")
List<User> getSelect();
修改核心配置文件
<mappers>
<mapper class="com.sydgm.dao.UserMapper"/>
</mappers>
本质:反射实现机制
底层:动态代理
// 根据id查询User对象
@Select("select * from mybatis.user where id = #{i}")
User getUserById(int i);
// 方法存在多个参数
@Select("select * from mybatis.user where id = #{id} and name = #{name}")
User getUserBy(@Param("id") int i, @Param("name") String name);
//引用类型不需要写参数
@Insert("insert into mybatis.user (id,name,pwd) values (#{id},#{name},#{password}) ")
int addUser(User user );
// 改
@Update("update mybatis.user set name = #{name},pwd = #{password} where id = #{id}")
int update(User user);
// 删除
@Delete("delete from mybatis.user where id = #{uid}")
int delete(@Param("uid") int id);
}
关于@Param()注解
基本类型的参数或者String类型,需要加上
引用类型不需加
如果只有一个基本类型的话,可以忽略,但是建议都加上
在SQL中引用的就是这里的@Param()中设置的属性名
9.Lombok
作用:在简单的pojo类中简化业务
使用步骤:
1.安装插件
2.在项目中导入Lombok的jar包 【maven依赖】
3.在实体类中加注解
@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
Code inspections
Refactoring actions (lombok and delombok)
@Data: 无参构造 ,get set toString hashCode equals
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private Integer id;
private String name;
private String password;
10.多对一的处理
按照查询嵌套处理:
1.查询所有的学生信息
2.根据查询出来的学生tid找到对应的老师
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sydgm.dao.StudentMapper">
<select id="getStudent" resultMap="StudentTeacher">
select * from mybatis.student;
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from mybatis.teacher;
</select>
</mapper>
一对多:
环境搭建:
@Data
public class Teacher {
private String name;
private int id;
// 一对多的包含关系
private List<Student> studentList;
}
@Data
public class Student {
private int id;
private String name;
// 多对一
private int tid;
按照结果查询
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--configuration核心配置文件-->
<mapper namespace="com.sydgm.dao.TeacherMapper">
<select id="getTeacher01" resultMap="TeacherStudent01">
select s.id sid ,s.name sname ,t.name tname,t.id tid
from mybatis.student s ,mybatis.teacher t
where s.tid = t.id and t.id = #{tid}
</select>
<resultMap id="TeacherStudent01" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="studentList" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
</mapper>
小结
1.关联 – association 【多对一】
2.集合 --collection 【一对多】
javaType & ofType
1.javaType用来指定实体类中属性的类型
2.ofType 用来指定映射到List或者集合中的pojo类型,泛型中的类型
注意点:
保证slq的可读性 尽量保证通俗易懂
注意一对多和多对一,属性名和字段的问题
建议使用Log4j
面试必问:
·Mysql引擎
·InnnoDB底层
·索引
·索引优化 !
12.动态SQL
所谓的动态SQL 本质还是slq语句,只是我我们可以在sql层面,去执行一个逻辑代码:
,就是根据不同的条件生成不同的sql语句
搭建环境:
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
if:
表示 如果有 title 走 title
有author 走 author
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分
<select id="blogIf" 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>
if的固定格式
where:
where标签: 在sql语句中 where 的后面不能直接跟 and
where title = #{} and author = #{author}//正确写法
where and author = #{author} //错误写法
where出现了 很智能 自动把and去掉了
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.blog
<where>
<if test="title != null">
title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</where>
</select>
set:
set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号
<update id="updateBlog" parameterType="map">
update mybatis.blog
<set>
<if test="title != null">
title = #{title},
</if>
<if test="author != null">
author = #{author}
</if>
where id = #{id}
</set>
</update>
choose(when,otherwise):
当选择choose标签之后
里面的when标签就像java中的 switch case 选择 满足条件的执行
而且只要执行一个就退出 不再执行其他的when
<select id="queryBlogChoose" parameterType="map" resultType="blog">
select * from mybatis.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>
13.缓存
什么是缓存【Cache】?
存在内存中的临时数据
将用户经常查询的数据放在缓存(内存 )中,用户去查询数据就不用去磁盘上查询
解决了高并发系统的性能问题
为什么使用缓存?
减少和数据库的交互次数,减少系统开销,提高系统效率
什么样的数据能使用缓存?
经常查询并且不经常改变的数据,可以使用缓存
13.1Mybatis缓存
- Mybatis包含 一个非常强大的查询缓存机制,可以非常方便的定制和配置缓存
- Mybatis系统默认定义了两级缓存,一级缓存和二级缓存
- 默认情况下,只有一级缓存开启(SqlSeesion级别的缓存,也成为本地缓存)
- 二级缓存需要手动开启和配置,他是基于namespace级别的缓存
- 为了提高拓展性,Mybatis定义了缓存接口Cache,我们可以通过实现Cache接口来自定义二级缓存
13.2 一级缓存
- 一级缓存也叫本地缓存 : SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要在去数据库
测试
public void queryBuId() {
SqlSession Sqlsession = MybatisUtilsTest.getSqlSession();
UserMapper userMapper = Sqlsession.getMapper(UserMapper.class);
// 第一次查询 测试根据相同的id查询用户
User user01 = userMapper.queryById(1);
// 第一次查询 测试根据相同的id查询用户 这次查询在缓存中拿,不需要再连接数据库
User user02 = userMapper.queryById(1);
System.out.println(user01 == user02);
Sqlsession.close();
}
缓存失败的情况:
1.查询不同的东西
2.增删改操作,可能会改变数据,所以必定会刷新缓存
3.手动清理缓存
小结:
一级缓存是默认开启的,只在一次SqlSession中有效,也就是拿到连接到关闭连接这个区间段
一级缓存就是一个Map
13.3二级缓存
- 二级缓存也叫做全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个接口对应一个二级缓存
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
- 如果当前会话关闭了,这个会话的一级缓存就没了,但是由于我们开启了二级缓存,一级缓存中的数据会保存到二级缓存中
- 新的会话查询信息,就可以从而二级缓存中获取内容
- 不同的mapper查出来的数据
步骤:
1.在核心配置文件中,开启全局缓存
<setting name="cacheEnable" value="true"></setting>
2.在要使用二级缓存的Mapper中开启
<!--在当前Mapper.xml文件中使用二级缓存-->
<cache/>
也可以自定义参数
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
3.测试一下创建二级缓存后
@Test
public void queryById() {
SqlSession session = MybatisUtilsTest.getSqlSession();
SqlSession session01 = MybatisUtilsTest.getSqlSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
// session关闭后 将一级缓存中的数据提交到二级缓存中
User user01 = userMapper.queryById(1);
session.close();
// 再次访问相同的数据
UserMapper userMapper1 = session01.getMapper(UserMapper.class);
User user02 = userMapper1.queryById(1);
session01.close();
System.out.println(user01 == user02);
}
问题:
1.我们需要将实体类序列化!否则就会报错
小结::
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有的数据都会先放在一级缓存中
- 只有将会话提交,或者关闭的时候,才会提交到二级缓存中去
![image-20211001145106469](https://i-blog.csdnimg.cn/blog_migrate/29d5b2dd08c7d756db8d0d5a4db41865.png)
13.4自定义缓存- ehcache
除了上述自定义缓存的方式,你也可以通过实现你自己的缓存,或为其他第三方缓存方案创建适配器,来完全覆盖缓存行为。
Ehcache是一种广泛使用的开源java分布式缓存,主要面向通用缓存
导包
<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
再mapper.xml中配置指定ehcache缓存实现
MyBatis的实现原理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-otWbuSRP-1633973680600)(C:\Users\申一丁\AppData\Roaming\Typora\typora-user-images\image-20211001164420254.png)]
BUG合集
1.最好不要在mybatis-config.xml 中添加中文注释