0%

mybatis chapter1

MyBatis 快速入门

Mybatis示例

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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"/>
<configuration>
<properites>
<property name = "username" value ="root"/>
<property name = "id" value = "123"/>
</properites>
<settings>
<setting name="cacheEnabled" value = "true"/>
</settings>
<typeAliases>
<typeAlias type = "com.xxx.Blog" alias = "Blog"/>
</typeAliases>
<enviroments default = "development">
<enviroment id = "development">
<transcationManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value = "com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</enviroment>
</enviroments>
<mappers>
<mapper resource="com/***/BlogMapper.xml"/>
</mappers>
</configuration>
</xml>

执行的java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Main {
public static void main(String[] args) throws Exception {
String resource = "com/xxx/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuillder().build(inputStream);

SqlSession sqlsession = sqlSessionFactory.openSession();
try {
Map<String,Object> parameter = new HashMap<>();
parameter.put("id", 1);
Blog blog = sqlSession.selectOne("com.xxx.BlogMapper.selectBlogDetails", parameter);
//
} catch(Exception e) {
e.printStackTrace();
}
}
}

MyBatis 整体架构

基础支持层

  • 反射模块

  • 类型转换模块

    jdbcType和JavaType之间类型做转换

  • 日志模块

  • 资源加载模块

    对类加载器进行封装

  • 解析器模块

    对Xpath进行封装 为config处理提供支持

    为处理sql语言中的占位符提供支持

  • 数据源模块

  • 事务管理

  • 缓存模块

  • Binding模块

核心处理层

  • 配置解析

  • Sql解析与sripting 模块

  • Sql执行

    sqlSession -> executor -> statementHandler -> parameterHandler -> statement -> db -> resultSet ->ResultSetHandler -> StatementHandler ->executor -> sqlSession