一、 MyBatis了解
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通 Java 对象)为数据库中的记录。---来自官网
二、MyBatis 整体架构
2.1 MyBatis 执行SQL流程图示
2.2 各个组件解析了解
2.2.1 Mybatis配置文件(mybatis-config.xml)
https://mybatis.org/mybatis-3/zh/configuration.html
<?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>
<!-- 配置设置
https://mybatis.org/mybatis-3/zh/configuration.html
-->
<settings>
<setting name="" value=""/>
</settings>
<!-- 标签用于配置环境信息-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:/home/hdj/db/h2db"/>
<property name="username" value="admin"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!-- Mapper文件-->
<mappers>
<mapper resource="mybatis/UserMapper.xml"/>
</mappers>
</configuration>
2.2.2 SqlSessionFactory
SqlSessionFactory使用SqlSessionFactoryBuilder对象获得的,SqlSessionFactoryBuilder可以通过预先定制的configuration或者xml配置文件的实例构建出SqlSessionFactory,SqlSessionFactory是线程安全的,一旦被创建,应用在执行期间都会存在,SqlSessionFactory也是创建SqlSession的工厂。可以通过SqlSession.openSession()创建SqlSession对象。
2.2.3 SqlSession
SqlSession是MyBatis提供的面向用户的API,表示和数据库交互时的会话对象,用于完成数据库的增删改查功能。
2.2.4 Executor执行器
- SimpleExecutor
- ResueExecutor
- BatchExecutor
Executor是MyBatis的SQL执行器,MyBatis中对数据库所有的增删改查操作都是由Executor组件完成的。
2.2.5 MappedStatement
MappedStatement:MappedStatement用于描述Mapper中的SQL配置信息,是对MapperXML配置文件中
2.2.6 TypeHandler 类型转换器
TypeHandler是MyBatis中的类型处理器,用于处理Java类型与JDBC类型之间的映射。它的作用主要体现在能够根据Java类型调用PreparedStatement或CallableStatement对象对应的setXXX()方法为Statement对象设置值,而且能够根据Java类型调用ResultSet对象对应的getXXX()获取SQL执行结果。
2.3 MyBatis 中的工具类了解
- SQL 语句构建器
- ScriptRunner 执行sql脚本
- SqlRunner操作数据库
- MetaObject 反射工具类
- ObjectFactory是MyBatis中的对象工厂
- ProxyFactory是MyBatis中的代理工厂
三、MyBatis 入门例子
3.1 创建Maven项目,引入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>MyBatis-Learning</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<mybatis-version>3.5.5</mybatis-version>
<h2-version>1.4.200</h2-version>
<lombox-version>1.18.12</lombox-version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis-version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2-version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombox-version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<!-- 描述存放资源的目录,该路径相对POM路径-->
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
3.2 创建表数据(自行连接H2)
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
insert into `user` (`id`,`name`,`age`) values (1, 'Jerry', 27);
insert into `user` (`id`,`name`,`age`) values (2, 'Angel', 25);
3.4 创建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="org.h2.Driver"/>
<property name="url" value="jdbc:h2:/home/hdj/db/h2db;AUTO_SERVER=TRUE"/>
<property name="username" value="admin"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<!-- Mapper文件-->
<mappers>
<mapper resource="mybatis/UserMapper.xml"/>
</mappers>
</configuration>
3.5 MyBatis 操作
实体类
@Data
public class User {
private Integer id;
private String name;
private Integer age;
}
DAO接口
public interface UserMapper {
List<User> selectAll();
}
UserMapper.xml 文件(与UserMapper接口同一文件夹下)
<?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="cn.hdj.mybatis.demo.dao.UserMapper">
<select id="selectAll" resultType="cn.hdj.mybatis.demo.entity.User">
select * from user
</select>
</mapper>
查询 ```xml public class SqlSessionFactoryBuildWithXml {
public static void main(String[] args) throws IOException {
//读取配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//构造SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建SqlSession
try (SqlSession session = sqlSessionFactory.openSession()) {
//获取Mapper接口
UserMapper mapper = session.getMapper(UserMapper.class);
//执行sql
List<User> users = mapper.selectAll();
System.out.println(users);
}
}
```
四、扩展知识点
4.1 MyBatis 命名空间的作用有两个
- 利用更长的全限定名来将不同的语句隔离开来
-
4.2 Java SPI 机制
https://crossoverjie.top/2020/02/24/wheel/cicada8-spi/
4.3 JDBC 连接步骤
(1)与数据源建立连接。
- (2)执行SQL语句。
- (3)检索SQL执行结果。
-
4.4 JDBC事务
自动提交模式
- 事务隔离级别
- 脏读
- 不可重读
- 幻影读
- 保存点
4.5 如何自定义存放Mapper.xml文件路径
- UserMapper 接口与UserMapper.xml 不在同一文件夹内,会报错?
https://my.oschina.net/wangdaoliang/blog/652266
项目地址
https://github.com/h-dj/Mybatis-Learning
参考
- http://mybatis.org/spring/zh/
- https://mybatis.org/mybatis-3/zh/index.html
- https://juejin.im/post/5ecd3493e51d45786973be27?utm_source=gold_browser_extension
- 面试题 https://my.oschina.net/zudajun/blog/747682
- H2 https://juejin.im/entry/59bf83ae6fb9a00a45516ca8
- JDBC规范 https://download.oracle.com/otndocs/jcp/jdbc-4_2-mrel2-spec/index.html
- JTA 规范 http://download.oracle.com/otndocs/jcp/jta-1.1-spec-oth-JSpec/?submit=Download
- JNDI规范文档:https://docs.oracle.com/cd/E17802_01/products/products/jndi/javadoc/
- MyBatis xml配置文件https://mybatis.org/mybatis-3/zh/configuration.html
- https://juejin.im/entry/5b9886735188255c960c1bec