Mybatis
官方中文文档(该笔记流程基于官网教程 及 狂神说Mybatis教程)
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。
MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。
MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
优势:
- 简化传统 JDBC 代码,框架化自动化。
- 解出 sql 与程序代码的耦合,sql与代码分离。
- 提供映射标签,提供动态sql。
持久化与持久层
数据持久化
- 持久化:将数据在持久状态和瞬时状态转化的过程
- 持久状态:硬盘
- 瞬时状态:内存(内存数据断点即失)
- 持久层:完成持久化工作的代码层(块)
入门案例
maven依赖:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
从 XML 中构建 SqlSessionFactory
每个基于 MyBatis 的应用都是以一个 SqlSessionFactory 的实例为核心的。SqlSessionFactory 的实例可以通过 SqlSessionFactoryBuilder 获得。
而 SqlSessionFactoryBuilder 则可以从 XML 配置文件或一个预先配置的 Configuration 实例来构建出 SqlSessionFactory 实例。
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
下面开始创建项目:
数据库 JDBC 配置
Resource 包下
—— 新建 mybatis-config.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>
<properties resource="jdbc.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.username}"/>
<property name="password" value="${db.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>-->
</mappers>
</configuration>
Resource 包下
—— 新建 db.properties
db.driver = "com.mysql.jdbc.Driver"
db.url = "jdbc:mysql://localhost:3306/mybatis_database?useSSL=true&userUnicode=true&characterEncoding=UTF-8"
db.username = "root"
db.password = "root123"
Mybatis 工具类配置
新建 Utils 包
—— 新建 MybatisUtils.java
public class MybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
POJO 类创建
新建 POJO 包
—— 新建 User 类
public class User {
private int id;
private String name;
private String pwd;
// 生成 无参构造 有参构造
// 生成 Getter Setter
}
Mapper 映射
由原来 创建 UserDao 接口, 创建 UserDaoImpl 继承接口来写sql,
转变成了一个 Mapper 配置文件来充当实现类
新建 Dao 包
—— 新建 UserMapper.interface
public interface UserMapper {
List<User> getUserList();
}
—— 新建 UserMapper.xml
-
resultType:类列表
-
resultMap:各种类的集合
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace绑定一个对应的Dao/Mapper接口上-->
<mapper namespace="org.dao.UserMapper">
<select id="getUserList" resultType="org.pojo.User">
select * from User
</select>
</mapper>
目录展示:
数据库测试
测试类
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for(User user:userList){
System.out.println(user.toString());
}
sqlSession.close();
}
运行可能的报错
-
Cause: java.io.IOException: Could not find resource org.dao.UserMapper.xml
需要在 mybatis-config 中注册 Mapper,mapper.xml 全路径,且把路径中 “.” 换成 “/”.
<mappers> <mapper resource="org/dao/UserMapper.xml"/> </mappers>
-
测试时,找不到资源文件
资源文件未生成在 target 目录中, 配置资源过滤,防止资源导出失败。
<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>
注意点
SqlSession
- 每个线程都应该有它自己的 SqlSession 实例。
- 最佳的作用域是请求或方法作用域。
- 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。
- 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。
流程
从外部引入数据库配置文件
创建实体类
创建 Mapper 接口,创建 Mapper 映射
编写测试类
增删改查
注意事项
-
在 Mapper.xml 中进行增删改时,传入类实例参数后,写sql语句传参时,参数不需要带类名,直接写属性名
但需写 parameterType=“类全路径”,(反射机制),后期在配置文件里起别名后可直接用别名。
举例:( 参数传递形式:
#{参数}
)void addUser(User user);
<insert id="addUser" parameterType="org.pojo.User"> insert into mybatis_database.user(id, name, pwd) values(#{id}, #{name}, #{pwd}) </insert>
@Test public void testAddUser(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper userMapper = sqlSession.getMapper(UserMapper.class); User user = new User(1, "张三", "admin"); userMapper.addUser(user); sqlSession.commit(); sqlSession.close(); }
-
增改时,需要在
sqlSession
关闭前提交事务:sqlSession.commit();
不然数据库查不到改动。
万能Map
void addUserByMap(Map<String, Object> map);
<insert id="addUserByMap" parameterType="map">
insert into mybatis_database.user(id, pwd) values(#{userId}, #{userPwd});
</insert>
@Test
public void testAddUserByMap(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
HashMap<String, Object> map = new HashMap<>();
map.put("userId", 6);
map.put("userPwd", "lqLqLq");
userMapper.addUserByMap(map);
sqlSession.commit();
sqlSession.close();
}
如果实体类或数据库中的表,字段或参数过多,考虑使用Map
mapper 传多个参数
方法一:万能Map
方法二:在 mapper 接口中,写两个参数; 在 mapper.xml 中用 #{param1}, #{param2} 来取值
public List<User> selectAllByLimitByArgs(int startIndex, int pageSize);
<select id="selectAllByLimitByArgs" parameterType="_int" resultMap="userMap">
select * from user limit #{param1}, #{param2}; // 关键点
</select>
@Test
public void testSelectAllByLimitByArgs(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = userMapper.selectAllByLimitByArgs(1, 2);
for(User user:userList){
System.out.println(user.toString());
}
sqlSession.close();
}
总结
Map类型传递参数,直接在sql中取键值即可
对象传递参数,直接在sql中取属性值即可
基本参数类型传参,可以直接取到
配置解析
- configuration(配置)
- properties(属性) 【需掌握】
- settings(设置) 【需掌握】
- typeAliases(类型别名) 【需掌握】
- typeHandlers(类型处理器)
- objectFactory(对象工厂)
- plugins(插件)
- environments(环境配置) 【需掌握】
- environment(环境变量)
- transactionManager(事务管理器)
- dataSource(数据源)
- environment(环境变量)
- databaseIdProvider(数据库厂商标识)
- mappers(映射器) 【需掌握】
属性
引入外部文件
<properties resource="db.properties"/>
引入外部文件的同时,额外声明子属性
<properties resource="db.properties">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis_database?useSSL=true&userUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root123"/>
</properties>
设置
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置 fetchType 属性来覆盖该项的开关状态。 | true | false | false |
mapUnderscoreToCamelCase | 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。数据库:last_name ⇔ \Leftrightarrow ⇔ java属性:lastName | true | false | False |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 |
类型别名
类型别名可为 Java 类型设置一个缩写名字,意在降低冗余的全限定类名书写。
基于xml配置文件:
<typeAliases>
<typeAlias alias="User" type="org.pojo.User"/>
</typeAliases>
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
<typeAliases>
<package name="domain.blog"/>
</typeAliases>
每一个在包 domain.blog
中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author
的别名为 author
;若有注解,则别名为其注解值。
插件
MyBatis Generator Core
MyBatis Generator - a code generator for MyBatis. (Mybatis代码生成器)
MyBatis Plus
An enhanced toolkit of Mybatis to simplify development.(Mybatis代码简化工具)
环境配置
MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中,不过要记住:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。
<environments default="development"> // 设置(切换)默认环境,
<environment id="development"> // 环境1
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
</dataSource>
</environment>
<environment id="test"> // 环境2
<transactionManager type="JDBC"/>
<dataSource type="POOLED"/>
</environment>
</environments>
事务管理器(transactionManager)
在 MyBatis 中有两种类型的事务管理器(也就是 type=“[JDBC | MANAGED]”):
连接数据库
连接池:
- dbcp
- c3p0
- druid
每次有新的数据库请求时,都要创建一个连接,会比较慢。连接池就是存放一定数量的连接对象。当某个对象使用完毕后,不进行销毁,而是放入连接池,留着给下一个数据库请求使用。
数据源类型:
**UNPOOLED **:这个数据源的实现会每次请求时打开和关闭连接。虽然有点慢,但对那些数据库连接可用性要求不高的简单应用程序来说,是一个很好的选择。 性能表现则依赖于使用的数据库,对某些数据库来说,使用连接池并不重要,这个配置就很适合这种情形。
POOLED : 这种数据源的实现利用“池”的概念将 JDBC 连接对象组织起来,避免了创建新的连接实例时所必需的初始化和认证时间。 这种处理方式很流行,能使并发 Web 应用快速响应请求。
JNDI : 这个数据源实现是为了能在如 EJB 或应用服务器这类容器中使用,容器可以集中或在外部配置数据源,然后放置一个 JNDI 上下文的数据源引用。
【Mybatis 默认的事务管理器是 JDBC , 默认连接池是 POOLED】
映射器(Mappers)
绑定MApper文件的三种主要方式:
方式一:指定资源文件名【推荐】
<mappers>
<mapper resource="org/dao/UserMapper.xml"/>
<mapper resource="org/dao/*Mapper.xml"/> // 有Spring框架才能用通配符,Mybatis自身不支持
</mappers>
方式二:使用class文件绑定(xml和注解能够同时生效)
<mappers>
<mapper class="org.dao.UserMapper"/>
</mappers>
方式二的注意点:
- 接口和 Mapper 配置文件必须同名
- 接口和 Mapper 配置文件必须在同一个包下
方式三:指定包名,对包名下的 Mapper 文件进行批量绑定(基于方式二,所以要满足方式二的注意点)
<mappers>
<package name="org.dao"/>
</mappers>
结果集映射
若 属性名 与 字段名 不一致, 会导致 查询数据库时,返回的结果中该属性为null,举例:
数据库字段名:
id | name | pwd
类属性名:
id | name | password
根据 sql 语句:
select * from user where id=#{id}
等价于
select name,pwd from user where id=#{id}
导致 查询出来的 pwd 无法映射到 类实例的 password 属性上
解决方法
-
sql 语句起别名
select name,pwd as password from user where id=#{id}
-
结果集映射
<resultMap id="userMap" type="User"> <result property="password" column="pwd"/> // 修改映射 </resultMap> <select id="getUserId" resultMap="userMap"> // 注意我们去掉了 resultType 属性 select * from User where id = #{id}; </select>
resultMap
元素是 MyBatis 中最重要最强大的元素。它可以让你从 90% 的 JDBC ResultSets
数据提取代码中解放出来,并在一些情形下允许你进行一些 JDBC 不支持的操作。
ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。
对于复杂的结果映射,后续一对多,多对一部分会详细讲解。
日志
一. 日志工厂
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | 未设置 |
- SLF4J
- LOG4J 【需掌握】
- LOG4J2
- JDK_LOGGING
- COMMONS_LOGGING
- STDOUT_LOGGING 【需掌握】
- NO_LOGGING
在Mybatis配置文件中进行配置,设置格式:
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
1. STDOUT_LOGGING
在 mybatiis-config.xml
中 <settings>
引入 STDOUT_LOGGING
即可,无需导包
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
日志结果:(不支持写入到 .log 文件,如其名一样只是在终端输出日志)
Opening JDBC Connection
Created connection 275310919.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1068e947]
==> Preparing: select * from user
==> Parameters:
<== Columns: id, name, pwd
<== Row: 1, 张三, admin
<== Row: 2, 李四, 654321
<== Row: 3, 叁叁, ACE
<== Row: 4, 王五, adcc
<== Row: 6, null, lqLqLq
<== Total: 5
User{id=1, name='张三', password='admin'}
User{id=2, name='李四', password='654321'}
User{id=3, name='叁叁', password='ACE'}
User{id=4, name='王五', password='adcc'}
User{id=6, name='null', password='lqLqLq'}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1068e947]
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1068e947]
Returned connection 275310919 to pool.
Process finished with exit code 0
2. LOG4J
Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等;我们也可以控制每一条日志的输出格式;通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程。最令人感兴趣的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。
maven 依赖
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Resource 下新建 log4j.properties , 添加如下内容
# 将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
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
mybaties-config 引入配置
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
分页
一次性查询某一区间上的内容,而不是所有数据。减少数据处理量,节省资源
使用 Limit 分页
select * from user limit startIndex,pagesize;
select * from user limit 0,2 # 从第0个元素开始,数两个
select * from user limit 3 # 前 n 个
使用 Mybatis 实现分页
也是使用 SQL 关键字 【limit】 进行分页, 记得传参即可。
注解开发
本质:反射机制实现
底层:动态代理(请求端请求目标对象(接口),真实对象实现该接口,代理对象(媒介)将真实对象交付给请求端)
不再需要 userMapper.xml
文件
<mappers>
<mapper class="org.mapper.UserMapper"/> // mapper 采用 class 的方式绑定
</mappers>
public interface UserMapper {
@Select("select * from user")
public List<User> selectAll();
}
Output:
User{id=1, name='张三', password='null'}
User{id=2, name='李四', password='null'}
User{id=3, name='叁叁', password='null'}
User{id=4, name='王五', password='null'}
User{id=6, name='null', password='null'}
这里需要对 password
属性和数据库里的 pwd字段做对应,需要 resultMap 做映射,但基于注解的开发会力不从心,对于复杂的sql语句,推荐用 xml 配置。
事务自动提交
// MybatisUtils.java
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession(true);
}
注解传参
@Select("select * from user where id=#{id}")
public User queryById(@Param("id") int id); // 多个参数后续再写 @Param("arg") Type arg 即可。
Param("argName")
相当于给指定参数指定新名字,例如
@Select("select * from user where id=#{pid}") // 需要改为新名字pid
public User queryById(@Param("pid") int id); // 指定新名字 pid
LOMBOK 插件
-
安装插件
-
导入依赖
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </dependency>
-
类或方法上加入注解
Lombok的优缺点
优点:
能通过注解的形式自动生成构造器、getter/setter、equals、hashcode、toString等方法,提高了一定的开发效率
让代码变得简洁,不用过多的去关注相应的方法
属性做修改时,也简化了维护为这些属性所生成的getter/setter方法等
缺点:
不支持多种参数构造器的重载
虽然省去了手动创建getter/setter方法的麻烦,但大大降低了源代码的可读性和完整性,降低了阅读源代码的舒适度
可添加的注解列表:
@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
@StandardException
@val
@var
experimental @var
@UtilityClass
【@Data
】:无参构造,get,set,toString,hashcode,equals
【@AllArgsConstructor
】:所有参的构造
【@NoArgsConstructor
】:无参构造
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private String password;
}
多对一
多个学生 关联 一个老师
一个老师 集合 多个学生
使用下述 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, '秦老师');
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');
创建学生老师类,设置学生多对一属性:
@Data
public class Student {
private int id;
private String name;
private Teacher teacher; // 关联,数据库字段名为 tid
}
@Data
public class Teacher {
private int id;
private String name;
}
若 现有需求,查询所有的学生,返回 学生(id, name)老师(name)
sql 语句如下:
select s.id, s.name, t.name from student s, teacher t where s.tid=t.id
使用 mybatis 实现
按照关系嵌套处理:
<!--
思路:(对应 mysql 子查询)
1. 查询所有学生
2. 根据学生的tid,查询tid=id的老师
-->
<select id="QueryAll" resultMap="studentTeacher"> // resultMap,对结果做重映射
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="QueryTeacherById"/>
</resultMap>
<select id="QueryTeacherById" resultType="teacher">
select * from teacher where id=#{id};
</select>
按照结果嵌套处理:
<!--
按结果嵌套处理(对应mysql联表查询)
思路:有点面向对象的意思
1. 写出能够导向结果的 sql 语句, 按照对象归属,进行嵌套
-->
<select id="QueryAll2" resultMap="studentTeacher2">
select s.id sid, s.name sname, t.name tname
from student as s, teacher as 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"> // 嵌套Teacher对象
<result property="name" column="tname"/>
</association>
</resultMap>
一对多
数据库与 【多对一】 一致,只是 POJO 类自身的对应关系不同
@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; // 老师 集合 学生
}
使用结果嵌套方式:
<mapper namespace="org.mapper.TeacherMapper">
<select id="QueryById" resultMap="teacherStudent">
select t.id tid, t.name tname, s.id sid, s.name sname
from teacher as t, student as s
where t.id = #{id} and s.tid = t.id;
</select>
<resultMap id="teacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student"> // 集合使用 ofType 来规定集合内(泛型)的元素类型
<result property="id" column="sid" />
<result property="name" column="sname" />
<result property="tid" column="tid" />
</collection>
</resultMap>
</mapper>
使用关系嵌套查询:
<select id="QueryById2" resultMap="teacherStudent2">
select *
from teacher
where id = #{id};
</select>
<resultMap id="teacherStudent2" type="Teacher">
<result property="id" column="id"/>
<result property="name" column="name"/>
<collection property="students" column="id" ofType="Student" select="QueryStudentByTid"/>
</resultMap>
<select id="QueryStudentByTid" resultType="Student">
select *
from student
where tid=#{id};
</select>
动态 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;
@Data
public class Blog {
private int id;
private String title;
private String author;
private Date createTime;
private int views;
}
生成数据库测试数据:
在 Utils 包下 创建 IDUtils,用于生成 ID 串
public class IDUtils {
public static String getID(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}
BlogMapper.xml:
<insert id="addBlog" parameterType="Blog">
insert into blog(id, title, author, create_time, views)
values (#{id}, #{title}, #{author}, #{createTime}, #{views})
</insert>
test.java:
@Test
public void testInsert(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
Blog blog = new Blog();
for(int i=0; i<10; i++){
Random r = new Random();
List<String> author = new ArrayList<>();
author.add("MONOKUMA");
author.add("MONOMI");
blog.setId(IDUtils.getID());
blog.setTitle("DAGAN IsLand-" + r.nextInt(10));
blog.setAuthor(author.get(i%2));
blog.setCreateTime(new Date());
blog.setViews(r.nextInt(9999));
blogMapper.addBlog(blog);
}
sqlSession.close();
}
IF 语句 + Where 语句
where语句:用于替代 SQL 语句中的 where 关键字(参考中文官方文档示例)。where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。
<select id="QueryBlogByArgs" parameterType="map" resultType="Blog">
select *
from blog
<where>
<if test="id != null">
id = #{id}
</if>
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null">
AND author like #{author}
</if>
<if test="views != null">
AND views > #{views} // 查找所有大于给定参数的 数据
</if>
</where>
</select>
@Test
public void testQueryByArgs(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
HashMap<String, String> titleMap = new HashMap<>();
titleMap.put("title", "DAGAN IsLand");
HashMap<String, String> authorMap = new HashMap<>();
authorMap.put("author", "MONOMI");
HashMap<String, Integer> viewsMap = new HashMap<>();
viewsMap.put("views", 4000);
List<Blog> result = blogMapper.QueryBlogByArgs(viewsMap);
for(Blog blog : result){
System.out.println(blog.toString());
}
}
如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。比如,和 where 元素等价的自定义 trim 元素为:
<trim prefix="WHERE" prefixOverrides="AND |OR ">
...
</trim>
prefixOverrides 属性会忽略通过管道符分隔的文本序列(注意此例中的空格是必要的)。上述例子会移除所有 prefixOverrides 属性中指定的内容,并且插入 prefix 属性中指定的内容。
choose、when、otherwise
有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。
还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员挑选的 Blog)。
<select id="findActiveBlogLike"
resultType="Blog">
SELECT * FROM BLOG WHERE state = ‘ACTIVE’
<choose>
<when test="title != null">
AND title like #{title}
</when>
<when test="author != null and author.name != null">
AND author_name like #{author.name}
</when>
<otherwise>
AND featured = 1
</otherwise>
</choose>
</select>
Set
用于动态更新语句的类似解决方案叫做 set。set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。比如:
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
这个例子中,set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。
来看看与 set 元素等价的自定义 trim 元素吧:
<trim prefix="SET" suffixOverrides=",">
...
</trim>
注意,我们覆盖了后缀值设置,并且自定义了前缀值。
SQL 片段
复用 SQL语句 的公共部分
提取公共部分:
<sql id="if-title-author-views">
<if test="title != null">
AND title like #{title}
</if>
<if test="author != null">
AND author like #{author}
</if>
</sql>
引用公共部分:
<select id="QueryBlogByArgs" parameterType="map" resultType="Blog">
<!-- ... -->
<include refid="if-title-author-views"/>
<!-- ... -->
</select>
注意事项:
- 最好基于单表 做复用
- 不要存在 where 标签
Foreach
类似于 SQL 语句:
select * from blog where 1=1 and (id=1, id=2, id=3)
动态 SQL 的一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。比如:
【将想要查询的元素 通过 Java ArrayList
等. 放入到 一个集合中,作为参数传入,并用 Foreach 标签实现遍历。】
<select id="selectPostIn" resultType="domain.blog.Post">
SELECT *
FROM POST P
WHERE ID in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")"> <!--指定开始符,元素分割符,结束符-->
<!--引用item-->
#{item}
</foreach>
</select>
foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!
实现 指定查询的 id 区间 的功能:
<select id="QueryByRange" parameterType="map" resultType="Blog">
select *
from blog
<where>
<foreach collection="ids" item="id"
open="and (" separator=" or " close=")">
id=#{id}
</foreach>
</where>
</select>
@Test
public void testQueryByRange(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
int[] range = new int[]{2, 8};
HashMap map = new HashMap();
ArrayList<Integer> ids = new ArrayList<>();
for(int i=range[0]; i<=range[1]; i++){
ids.add(i);
}
map.put("ids", ids);
List<Blog> result = blogMapper.QueryByRange(map); // 这里直接传 List 也可以,不用 map 封装
for(Blog blog : result){
System.out.println(blog.toString());
}
sqlSession.close();
}
缓存
连接数据库是非常耗资源的,通过对查询结果暂存(放在内存中),就不用从磁盘上(数据库)中查询,
来减少数据库资源的使用(解决高并发性能问题),缩短响应时间
读写分离:缓存
主从复制:哨兵模式
MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。分为 【一级缓存】 【二级缓存】 两种。
默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。 (返还SqlSession后即失效)
一级缓存
缓存周期:session范围内,本地会话缓存。测试:
@Test
public void testCache(){
SqlSession sqlSession = MybatisUtils.getSqlSession(); // 使用同一个 sqlsession
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
List<Blog> result = blogMapper.QueryByRange(new int[]{2, 5}); // 第一次查询
System.out.println(result.toString());
System.out.println("==========================================");
List<Blog> result2 = blogMapper.QueryByRange(new int[]{2, 5}); // 第二次查询
System.out.println(result2.toString());
System.out.println("==========================================");
System.out.println(result == result2);
sqlSession.close();
}
Log:
【org.apache.ibatis.transaction.jdbc.JdbcTransaction】-Opening JDBC Connection
【org.apache.ibatis.datasource.pooled.PooledDataSource】-Created connection 48914743.
【org.dao.BlogMapper.QueryByRange】-==> Preparing: select * from blog WHERE ( id=? or id=? ) // 查询数据库
【org.dao.BlogMapper.QueryByRange】-==> Parameters: 2(Integer), 5(Integer)
【org.dao.BlogMapper.QueryByRange】-<== Total: 2
[Blog(id=2, title=DAGAN IsLand-3, author=MONOKUMA, createTime=Sat Jan 21 11:09:07 CST 2023, views=8097), Blog(id=5, title=DAGAN IsLand-5, author=MONOMI, createTime=Sat Jan 21 11:09:07 CST 2023, views=9058)]
========================================== // 第二次没有查询数据库,直接返回的结果
[Blog(id=2, title=DAGAN IsLand-3, author=MONOKUMA, createTime=Sat Jan 21 11:09:07 CST 2023, views=8097), Blog(id=5, title=DAGAN IsLand-5, author=MONOMI, createTime=Sat Jan 21 11:09:07 CST 2023, views=9058)]
==========================================
true // 返回为true 两次查询结果具有相同的地址
【org.apache.ibatis.transaction.jdbc.JdbcTransaction】-Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@2ea6137]
【org.apache.ibatis.datasource.pooled.PooledDataSource】-Returned connection 48914743 to pool.
缓存逻辑:
- 映射语句文件中的所有 select 语句的结果将会被缓存。
- 映射语句文件中的所有 insert、update 和 delete 语句会刷新缓存。(整张表的缓存都会失效clear,缓存会从零开始记录)
- 缓存会使用最近最少使用算法(LRU, Least Recently Used)算法来清除不需要的缓存。
- 缓存不会定时进行刷新(也就是说,没有刷新间隔)。
- 缓存会保存列表或对象(无论查询方法返回哪种)的 1024 个引用。
- 缓存会被视为读/写缓存,这意味着获取到的对象并不是共享的,可以安全地被调用者修改,而不干扰其他调用者或线程所做的潜在修改。
一级缓存作用不大,因为每次请求都会重新连接 session。
二级缓存
显式开启全局缓存
设置名 | 描述 | 有效值 | 默认值 |
---|---|---|---|
cacheEnabled | 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。 | true | false | true |
<setting name="cacheEnabled"value="true"/>
-
二级缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存
-
基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
-
工作机制
-
一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中;
-
如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中;
-
新的会话查询信息,就可以从二级缓存中获取内容;
-
不同的 mapper 查出的数据会放在自己对应的缓存(map)中;
-
要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:(基于namespace级别的缓存,对应一个mapper)
<mapper namespace="...">
...
<cache/>
...
</mapper>
自定义二级缓存:
<cache
eviction="FIFO"
flushInterval="60000"
size="512"
readOnly="true"/>
eviction :
LRU
– 最近最少使用:移除最长时间不被使用的对象。FIFO
– 先进先出:按对象进入缓存的顺序来移除它们。SOFT
– 软引用:基于垃圾回收器状态和软引用规则移除对象。WEAK
– 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。
默认的清除策略是 LRU。
@Test
public void testCache2(){
System.out.println("==========================================");
SqlSession sqlSession = MybatisUtils.getSqlSession(); // 第一个 Sqlsession
BlogMapper blogMapper = sqlSession.getMapper(BlogMapper.class);
List<Blog> result1 = blogMapper.QueryByRange(new int[]{2, 5});
System.out.println(result1.toString());
sqlSession.close();
System.out.println("==========================================");
SqlSession sqlSession2 = MybatisUtils.getSqlSession(); // 第二个 Sqlsession
BlogMapper blogMapper2 = sqlSession2.getMapper(BlogMapper.class);
List<Blog> result2 = blogMapper2.QueryByRange(new int[]{2, 5});
System.out.println(result2.toString());
sqlSession2.close();
System.out.println(result1 == result2); // true
}
出现的问题:mapper文件中 cache不加参数,会报 类没有序列化 的错误 :
Error serializing object. Cause: java.io.NotSerializableException: org.pojo.Blog
解决:
方法一:
public class Blog implements Serializable{
private String id;
// .....
private int views;
}
这时终端输出 会出现 (result1 == result2) = false
,是因为 序列化是深拷贝,所以反序列化后的对像和原对象不是同一个对象,故哈希值不同。
System.out.println(result1 == result2); // false
方法二:
设置缓存参数:
readonly = true
.
缓存原理
自定义缓存
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.2.3</version>
</dependency>
在需要使用缓存的 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"/>
<!--
name:缓存名称。
maxELementsInMemory:缓存最大数目
maxELementsonDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overfLowToDisk:是否保存到磁盘,当系统宕机时。
timeToIdLeSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false付象不是永久有效时使用,可选属性,默认值是9,也就
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal.=false对象不是永久有
diskPersistent:是否级存虚拟机重启蝴数据Whether the disk store persists between restarts of the virtual Machine.The defa
diskSpooLBuffersizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是38MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervaLSeconds:磁盘失效线程运行时间间隔,默认是128秒。
memoryStoreEvictionPoLicy:当达到naxELementsInMemory.限制时,Ehcache将会根据指定的策略去清理内存。默认策略是RU(最近最少使用)
cLearOnFLush:内存数量最大时是否清除。
memorystoreEvictionPoLicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出
LFU,Less Frequently Used,就是上面例子中使用的策略,直白一点就是诽一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,h
LU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方米缓存新的元素的时候,那么现有
-->
</ehcache>
后面会使用 Redis 非关系型数据库,做缓存 key-value 的形式存储数据。
这里只是简要介绍 自定义缓存的方法。
e"
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"/>
<!--
name:缓存名称。
maxELementsInMemory:缓存最大数目
maxELementsonDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overfLowToDisk:是否保存到磁盘,当系统宕机时。
timeToIdLeSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false付象不是永久有效时使用,可选属性,默认值是9,也就
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal.=false对象不是永久有
diskPersistent:是否级存虚拟机重启蝴数据Whether the disk store persists between restarts of the virtual Machine.The defa
diskSpooLBuffersizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是38MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervaLSeconds:磁盘失效线程运行时间间隔,默认是128秒。
memoryStoreEvictionPoLicy:当达到naxELementsInMemory.限制时,Ehcache将会根据指定的策略去清理内存。默认策略是RU(最近最少使用)
cLearOnFLush:内存数量最大时是否清除。
memorystoreEvictionPoLicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出
LFU,Less Frequently Used,就是上面例子中使用的策略,直白一点就是诽一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,h
LU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方米缓存新的元素的时候,那么现有
-->
```
后面会使用 Redis 非关系型数据库,做缓存 key-value 的形式存储数据。
这里只是简要介绍 自定义缓存的方法。