MyBatis 学习记录1 一个简单的demo

时间:2024-10-01 09:35:20

主题

  最近(N个月前)clone了mybatis的源码..感觉相比于spring真的非常小...然后看了看代码觉得写得很精简...感觉我的写代码思路和这个框架比较相似(很难具体描述...就是相对来说比较容易理解作者想干嘛,虽然也没有注释..)...所以打算好好研究学习下.

从1个简单的DEMO来入门

 package test.test;

 import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import test.mapper.UserMapper;
import test.model.User; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream; public class MyTest {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = new FileInputStream(resource);
//从 XML 中构建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
UserMapper mapper = session.getMapper(UserMapper.class);
User u = mapper.selectByPrimaryKey(1);
System.out.println(u); User u2 = mapper.selectByPrimaryKey(1);
System.out.println(u2);
} finally {
session.close();
}
}
}

这段代码的输出如下:

Connected to the target VM, address: '127.0.0.1:51496', transport: 'socket'
2018-09-24 10:13:47,501 DEBUG [main] logging.LogFactory : Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Mon Sep 24 10:13:47 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Created connection 13928019.
Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@d48653]
==> Preparing: select id, user_id, user_name, real_name, email, creator_uid, modifier_uid, created_at, updated_at, del from user where id = ? and del = 0
==> Parameters: 1(Integer)
<== Columns: id, user_id, user_name, real_name, email, creator_uid, modifier_uid, created_at, updated_at, del
<== Row: 1, 1, test, realName, jyzjyz12@163.com, 1, 1, 2018-09-24 10:10:43.0, 2018-09-24 10:10:46.0, 0
<== Total: 1
User{id=1, userId=1, userName='test', realName='realName', email='jyzjyz12@163.com', creatorUid=1, modifierUid=1, createdAt=Mon Sep 24 10:10:43 CST 2018, updatedAt=Mon Sep 24 10:10:46 CST 2018, del=false}
User{id=1, userId=1, userName='test', realName='realName', email='jyzjyz12@163.com', creatorUid=1, modifierUid=1, createdAt=Mon Sep 24 10:10:43 CST 2018, updatedAt=Mon Sep 24 10:10:46 CST 2018, del=false}
Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@d48653]
Disconnected from the target VM, address: '127.0.0.1:51496', transport: 'socket'
Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@d48653]
Returned connection 13928019 to pool.

就几行代码.我就debug大致看了看都做了哪些事情.

初始化SqlSessionFactory时候各种对象之间的关系

SqlSessionFactory一般一个应用只会创建1个.在程序初始化的时候创建.从这个对象中可以获取SqlSession,SqlSession是Facade设计模式.SqlSession可以获取Mapper.获取了Mapper就可以进行各种查询了.

要创建SqlSessionFactory可以通过SqlSessionFactoryBuilder的build方法来创建,build可以有很多可选的参数,比如inputstram,file...等等..最终都是转化成configuration.

转化成configuration的时候也需要借助于XMLConfigBuilder的parse方法.

对象之间关系大致如图:

MyBatis 学习记录1 一个简单的demo

1.我们需要的是SqlSession.我们一般和它打交道.从它里面可以获取Mapper

2.SqlSession需要通过SqlSessionFactory来创建.

3.SqlSessionFactory需要通过SqlSessionFactoryBuilder来build.同时build的时候需要一份配置,这个配置就是Configuration,而Configuration对象需要使用XMLConfigBuilder来解析XML生成

同时需要指定使用配置中的哪个环境?因为一个配置可以有多个环境,区别qa,dev,prod....等等.还可以传入参数,因为配置URL,USERNAME,PASSWORD的时候可以传入占位符.

MyBatis 学习记录1 一个简单的demo

MyBatis 学习记录1 一个简单的demo

4.创建好SqlSessionFactory以后我们就可以通过openSession方法来获取SqlSession了.SqlSession要执行SQL或者给你Mapper.需要用到executor来真正执行SQL,executor要执行SQL肯定也需要用到TransactionFactory创建的Transaction,Transaction对象要能正确执行事务,肯定需要用到Datasource,事务隔离级别level,是否autoCommit等参数.这些参数可以在Configuration(Environment)里获取

5.executor是装饰着的设计模式.默认返回的是CacheExecutor内部装饰着SimpleExecutor.SimpleExecutor中存在着mybatis的一级缓存,从我们的打印日志中可以看出来.我们SQL只打印了一次.所以同一个Mapper多次查询同样的SQL是有一级缓存的.如果你换了一个SqlSession,那就无效了.所以一级缓存是在SqlSession级别的.而二级缓存在CacheExecutor中.不同的SqlSession可以共享二级缓存.

以上就是初始化阶段对象之间的一些关系对的简单梳理