Mybatis
笔记备忘
参考视频:B站狂神说Mybatis
前言
Mybatis实质简化JDBC操作
环境:
- JDK1.8
- mysql5.7或8.0
- maven 3.6.1
- IDEA
回顾:
- JDBC
- Mysql
- Java基础
- Maven
- Junit
Mybatis官网:https://mybatis.org/mybatis-3/zh/index.html
1、简介
1.1、什么是 MyBatis?
- MyBatis 是一款优秀的持久层框架。
- 它支持自定义 SQL、存储过程以及高级映射。
- MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
- MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
- MyBatis本是apache的一个开源项目iBatis,2010年这个项目由apache software foundation迁移到了google code,并且改名为MyBatis。2013年11月迁移到Github。
1.2、如何获取Mybatis?
-
maven仓库
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency>
-
Github:https://github.com/mybatis/mybatis-3/releases
1.3、持久化
数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
- 内存:断电即失
- 数据库(jdbc) io文件持久化
1.4、持久层
Dao层,Service层,Controller层
-
完成持久化工作的代码块
-
层界限十分明显
1.5、为什么需要Mybatis?
-
方便
-
传统的JDBC代码太复杂,简化,框架,自动化
-
方便将数据存入到数据库中
-
优点
- 简单易学
- 灵活
- sql和代码的分离,提高了可维护性。
- 提供映射标签,支持对象与数据库的orm字段关系映射。
- 提供对象关系映射标签,支持对象关系组建维护。
- 提供xml标签,支持编写动态sql
-
用的人多,生态好
2、第一个MyBatis程序
思路:搭建环境->导入MyBatis->编写代码->测试
2.1、搭建环境
搭建数据库–纯sql示例
CREATE DATABASE `mybatis`;
USE `mybatis`;
CREATE TABLE `user`(
`id` INT(20) NOT NULL,
`name` VARCHAR(20) DEFAULT NULL,
`sex` VARCHAR(10) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT `user`(`id`,`name`,`sex`,`pwd`) VALUES
(1,'小明','男','123333'),
(2,'小红','女','43242342'),
(3,'小强','男','4234223');
环境
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<!-- <scope>test</scope>-->
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!--MyBatis驱动-->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
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.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
- 编写mybatis工具类
package com.future.utils;
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.InputStream;
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}catch (Exception e){
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
2.3、编写代码
-
实体类
package com.future.pojo; public class User { private int id; private String name; private String sex; private String pwd; public User() { } public User(int id, String name, String sex, String pwd) { this.id = id; this.name = name; this.sex = sex; this.pwd = pwd; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
-
Dao接口
public interface UserDao { // 获取用户名 List<User> getUserList(); }
-
接口实现类由原来的UserDaoImpl变为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.future.dao.UserDao"> <select id="getUserList" resultType="com.future.pojo.User"> select * from mybatis.user; </select> </mapper>
2.4、测试
MapperRegister是什么?
核心配置文件中注册mappers
-
junit测试
@Test public void test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserDao mapper = sqlSession.getMapper(UserDao.class); List<User> userList = mapper.getUserList(); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
3、CRUD
3.1、namespace
namespace中的包名要和Dao/mapper中接口包名一致。
3.2、Select
选择,查询语句
示例
<select id="getUserList" resultType="com.future.pojo.User">
select * from mybatis.user;
</select>
- id:对于namespace中的方法名
- resultType:sql语句的返回值
- parameterType:参数类型
-
接口
//根据ID查用户 User getUserById(int id);
-
sql
<select id="getUserById" parameterType="int" resultType="com.future.pojo.User"> select * from mybatis.user where id = #{id} </select>
-
测试
@Test public void getUserById(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.getUserById(2); System.out.println(user); sqlSession.close(); }
3.3、Insert
<!--插入一个用户-->
<insert id="addUser" parameterType="com.future.pojo.User">
insert into mybatis.user (id,name,sex,pwd) values (#{id},#{name},#{sex},#{pwd})
</insert>
增删改需要提交事物
测试
//增删改需要提交事物
@Test
public void addUser(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
int i = mapper.addUser(new User(4, "小明", "男", "432423"));
if(i > 0){
System.out.println("插入成功");
}
//提交事物
sqlSession.commit();
sqlSession.close();
}
3.4、Update
<!--修改-->
<update id="updateUser" parameterType="com.future.pojo.User">
update mybatis.user
set name = #{name},
sex = #{sex},
pwd = #{pwd}
where id = #{id};
</update>
3.5、Delete
<!--删除用户-->
<delete id="deleteUser" parameterType="int">
delete from mybatis.user where id = #{id}
</delete>
3.6、万能的Map
数据库表中的字段过多时,应该考虑使用map
//Map
int addUser2(Map<String,Object> map);
<insert id="addUser2" parameterType="map">
insert into mybatis.user (id,name,sex,pwd) values (#{userid},#{username},#{usersex},#{userpwd})
</insert>
@Test
public void addUser2(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
Map<String, Object> map = new HashMap<>();
map.put("userid",2);
map.put("username","wh");
map.put("usersex","男");
map.put("userpwd","43fdsdfssfds");
int i = mapper.addUser2(map);
if(i > 0){
System.out.println("插入成功");
}
//提交事物
sqlSession.commit();
sqlSession.close();
}
Map传递参数,直接在sql中取出Key即可!
对象传递参数,直接在sql中取出对象的属性即可!
只有一个基本类型的参数的情况下,可以直接在sql中取出!
多个参数用Map或者注解
3.7、模糊查询
-
java代码执行的时候传递通配符%%
List<User> userList = mapper.getUserLike("%小%");
-
在sql中拼接中使用通配符
select * from mybatis.user where name like "%"#{value}"%";
4、配置解析
4.1、核心配置文件
-
mybatis-config.xml
-
mybatis的配置文件包含了会深深影响mybatis行为的设置和属性信息
properties(属性) settings(设置) typeAliases(类型别名) typeHandlers(类型处理器) objectFactory(对象工厂) plugins(插件) environments(环境配置) environment(环境变量) transactionManager(事务管理器) dataSource(数据源) databaseIdProvider(数据库厂商标识) mappers(映射器)
4.2、环境配置(environments)
MyBatis 可以配置成适应多种环境
不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
配置多套运行环境
Mybatis默认的事物管理器就是JDBC,连接池:POOLED
4.3、属性Properties
我们可以通过properties属性来实现引用配置文件
这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。(db.properties)
db.properties
driver=com.mysql.cj.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/mybatis?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
username=root
password=123456
然后在核心配置文件中引入
<properties resource="db.properties"/>
- 可以直接引入外部文件
- 可以在其中增加一些属性
- 如果两个文件有同一个字段,会优先使用外部配置文件
4.4、类型别名(typeAliases)
- 类型别名可为 Java 类型设置一个缩写名字
- 它仅用于 XML 配置,意在降低冗余的全限定类名书写
<!--给实体类起别名-->
<typeAliases>
<typeAlias type="com.future.pojo.User" alias="User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean
<typeAliases>
<package name="com.future.pojo"/>
</typeAliases>
实体类较少时,使用第一种
实体类较多时,使用第二种
若有注解,则别名为其注解值
@Alias("author")
public class Author {
...
}
4.5、设置(settings)
这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为
内容比较多,查看https://mybatis.org/mybatis-3/zh/configuration.html#settings了解更多
4.6、其他配置
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- mybatis-generator-core
- mybatis-plus
- 通用mapper
4.7、映射器(mappers)
MapperRegistry:注册绑定我们的Mapper文件
- 方式一[推荐使用]
<mappers>
<mapper resource="com/future/dao/UserMapper.xml"/>
</mappers>
- 方式二:通过class文件绑定注册
<mappers>
<mapper class="com.future.dao.UserMapper"/>
</mappers>
注意点:
-
接口和Mapper必须同名
-
接口和Mapper必须在同一个包下
-
方式三:使用扫描包进行注入绑定
<mappers>
<package name="com.future.dao"/>
</mappers>
4.8、生命周期和作用域
理解我们之前讨论过的不同作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。
SqlSessionFactoryBulider
- 一旦创建了 SqlSessionFactory,就不再需要它了
- 局部变量
SqlSessionFactory
- 可以理解为:数据库连接池
- SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
- 因此 SqlSessionFactory 的最佳作用域是应用作用域
- 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式
SqlSession
- 连接到连接池的一个请求
- SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。
- 用完之后赶紧关闭,避免资源被占用。
这里的每一个Mapper代表一个具体的业务
5、解决属性名和字段名不一致的问题
解决方法
- sql语句中起别名
ResultMap
结果集映射
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的字段-->
<result column="id" property="id"/>
<result column="name" property="name"/>
<result column="sex" property="sex"/>
<result column="pwd" property="pwd"/>
</resultMap>
resultMap
元素是 MyBatis 中最重要最强大的元素- ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
6、日志
6.1、日志工厂
数据库操作出现异常,可以使用日志进行排错
之前:sout,debug
now:日志工厂
- SLF4J
- LOG4J(deprecated since 3.5.9) 【掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【掌握】
- NO_LOGGING
在Mybatis中具体使用哪一个,在设置中规定。
STDOUT_LOGGING标准日志输出
6.2、Log4j
什么是log4j
- Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件
- 我们也可以控制每一条日志的输出格式
- 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程
- 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码
-
导包log4j
<!-- https://mvnrepository.com/artifact/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/future.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{yyyy-MM-dd HH:mm:ss}][%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="LOG4J"/> </settings>
简单使用
-
在要使用log4j的类中,导入包import org.apache.log4j.Logger;
-
日志对象,参数为当前类的class
static Logger logger = Logger.getLogger(UserDaoTest.class);
-
日志级别
logger.info("info:进入testLog4j方法"); logger.debug("debug:进入testLog4j方法"); logger.error("error:进入testLog4j方法");
7、分页
为什么要分页?
- 减少数据的处理量
7.1、limlit分页
语法:SELECT * from user limit startIndex,pageSize;
使用Mybatis实现分页,核心SQL
-
接口
//分页 List<User> getUserByLimit(Map<String,Integer> map);
-
Mapper.xml
<!--分页--> <select id="getUserByLimit" parameterType="map" resultType="user"> select * from mybatis.user limit #{startIndex},#{pageSize} </select>
-
测试
@Test public void getUserByLimit(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); Map<String, Integer> map = new HashMap<>(); map.put("startIndex",0); map.put("pageSize",2); List<User> userList = mapper.getUserByLimit(map); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.2、RowBounds分页
不再使用SQL实现分页
-
接口
//分页RowBounds List<User> getUserByRowBounds();
-
mapper.xml
<!--分页RowBounds--> <select id="getUserByRowBounds" resultMap="UserMap"> select * from mybatis.user </select>
-
测试
@Test public void getUserByRowBounds(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //使用RowBounds实现分页 RowBounds rowBounds = new RowBounds(0, 2); List<User> userList = sqlSession.selectList("com.future.dao.UserMapper.getUserByRowBounds",null,rowBounds); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
7.3、前端插件
pageHelper
8、使用注解开发
8.1、面向接口编程
选择面向接口编程的根本原因:=解耦=,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,是的开发变得容易,规范性更好。
面向接口编程含义
在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是指按照这种思想来编程。
关于接口的理解
-
接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
-
接口的本身反映了系统设计人员对系统的抽象理解。
-
接口应有两类:
- 第一类是对一个个体的抽象,它可对应为一个抽象体(abstract class);
- 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);
-
一个体有可能有多个抽象面。抽象体与抽象面是有区别的。
8.2、注解开发
-
注解在接口上实现
@Select("select * from user") List<User> getUsers();
-
在核心配置文件中绑定接口
<mappers> <mapper class="com.future.dao.UserMapper"/> </mappers>
-
测试
@Test public void getUsers(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); //底层利用反射实现 UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.getUsers(); for (User user : userList) { System.out.println(user); } sqlSession.close(); }
本质:反射机制实现
底层:动态代理
8.3、自动提交事物
在MybatisUtils中
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
8.4、CRUD
在接口中添加注解。如@Select等。
关于@Param()注解
-
基本数据类型的参数或者String类型,需要加上
-
引用类型不需要加
-
如果只有一个基本类型,可以忽略,但是建议加上
-
我们在SQL中引用的就是这里@Param(“#id”)中设置的属性名。
9、Lombok
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
使用步骤
-
在idea中安装Lombok插件
-
都让lombok的jar包
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> </dependency>
-
方法
@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
常用(在类上加注解):
@Data:无参构造,get,set,tostring,hashcode,euqals @AllArgsConstructor:有参构造 @NoArgsConstructor:无参构造
10、多对一处理
多对一概念
- 多个学生对应一个老师
- 对于学生这边而言,关联…多个学生,关联一个老师【多对一】
- 对于老师而言,集合,一个老师有很多学生。
resource下的包名要和src下对应,并且包名要一级一级建,可以看target来debug
按照查询嵌套处理
<!--方法1-子查询-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id = #{tid}
</select>
按照结果嵌套处理
</select>
<!--方法2-按照结果查询-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
from student s,teacher t where s.tid = t.id
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
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;
}
按照结果嵌套处理
<!--按照结果嵌套查询
集合中的泛型要使用ofType取
-->
<select id="getTeacher2" 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"/>
<!--复杂属性,我们需要单独处理-->
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sid"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
按照查询嵌套处理
<!--子查询-->
<select id="getTeacher3" resultMap="TeacherStudent2">
select * from mybatis.teacher where id = #{id}
</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 mybatis.student where tid = #{tid}
</select>
小结
-
关联-association【多对一】
-
集合-collection【一对多】
-
javaType & ofType
- javaType 用来指定实体类中的类型
- 用来指定映射到List或者集合中的pojo类型,泛型中约束类型
注意点:
- 保证SQL可读性,保持通俗易懂
- 注意一对多和多对一,属性名和字段的问题
- 如果问题不好排查错误,可以使用日志
上面的SQL属于慢SQL,实际工作一定需要优化!!!
面试高频
- MySql引擎
- InnoDB底层原理
- 索引
- 索引优化!
12、动态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;
创建一个基础工程
- 导包
- 编写配置文件
- 编写实体类
- 编写实体类对应Mapper接口和Mapper.xml文件
IF
使用动态 SQL 最常见情景是根据条件包含 where 子句的一部分。
<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)
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
<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>
trim(where,set)
你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
所谓动态SQL,本质还是SQL语句,知识我们可以在SQL层面,去执行一个逻辑代码。
SQL片段
有时候会将一些功能的部分抽取出来,方便复用!
1、使用SQL标签抽取公共部分
<sql id="if-title-author">
<if test="title != null">
and title = #{title}
</if>
<if test="author != null">
and author = #{author}
</if>
</sql>
2、在需要用的地方使用include标签
<select id="queryBlogIF" parameterType="map" resultType="blog">
select * from mybatis.blog where 1=1
<include refid="if-title-author"></include>
</select>
注意事项:
- 最好基于单表来定义SQL片段
- 不要存在where标签
Foreach
<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 是 MyBatis 的强大特性之一。如果你使用过 JDBC 或其它类似的框架,你应该能理解根据不同条件拼接 SQL 语句有多痛苦,例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL,可以彻底摆脱这种痛苦。
13、缓存
13.1、简介
查询:连接数据库,耗资源
把一次查询的结果暂存在一个可以直接取到的地方---->内存-缓存
我们在此查询相同数据的时候,直接走缓存,就不用走数据库了。
-
什么是缓存【Cache】
- 存在内存中的临时数据
- 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上查询,从缓存中查询,提高了查询的效率,解决了高并发系统的性能问题。
-
为什么使用缓存?
- 减少与数据库的交互次数,减少系统开销,提高系统效率
-
什么样的数据能使用缓存?
- 经常查询并且不经常改变的数据
13.2、Mybatis缓存
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置,我们对 MyBatis 3 中的缓存实现进行了许多改进。
13.3、一级缓存
- 一级缓存也叫本地缓存:SqlSession
- 与数据库同一次会话期间查询到的数据会放在本地缓存中。
- 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库;
测试步骤
- 开始日志
- 测试一个Session中查询两次记录
- 查看日志输出
缓存失效的情况
- 查询不同的东西
- 增删改操作,可能会改变原来的数据,所以必定会刷新缓存!
- 查询不同的Mapper.xml
- 手动清理缓存!
小结:一级缓存默认是开启的,只在一次sqlSession中有效,也就是拿到连接到关闭连接这个区间段
13.4、二级缓存
- 二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
- 基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
- 工作机制
- 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
- 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存;
- 新的会话查询信息,就可以从二级缓存中获取内容;
- 不同mapper查出的数据会放在自己对应的缓存(map)中;
步骤
-
开启全局缓存
<!--显示开启全局缓存--> <setting name="cacheEnabled" value="true"/>
-
在当前mapper.xml中使用二级缓存
<!--在当前mapper.xml中使用二级缓存 --> <cache/>
-
可选参数
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
这个更高级的配置创建了一个 FIFO 缓存,每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,而且返回的对象被认为是只读的,因此对它们进行修改可能会在不同线程中的调用者产生冲突。
小结:
- 只要开启了二级缓存,在同一个Mapper下就有效
- 所有数据都会先放在一级缓存中
- 只有当会话提交或者关闭的时候,才会提交到二级缓存中!
13.5、Mybatis缓存原理
13.6、自定义缓存-ehcache
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认CacheProvider。Ehcache是一种广泛使用的开源Java分布式缓存。主要面向通用缓存,Java EE和轻量级容器。它具有内存和磁盘存储,缓存加载器,缓存扩展,缓存异常处理程序,一个gzip缓存servlet过滤器,支持REST和SOAP api等特点。
导包
<!-- 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中指定使用我们的ehcache缓存实现!
<!--在当前Mapper.xml中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
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"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
</ehcache>