mybatis框架底层原理分析
1,会话工厂创建分析
基于XML方式创建流程大致如下:
1,通过IO流读取配置文件
2,解析IO数据并进行封装(所有信息都会存储到Configuration对象中)
3,基于配置对象创建SqlSessionFactory对象
基于代码实现
package com.amdr;
import com.amdr.goods.dao.GoodsDao;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.junit.Before;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
/**
* @Description
* @Author Amdr
* @Date 2023/10/17
*/
public class TestBaseWithJava {
protected SqlSessionFactory sqlSessionFactory;
@Before
public void init() throws IOException {
/**
* 代码实现基于注解操作数据库的配置
*/
DataSource dataSource = new PooledDataSource("com.mysql.cj.jdbc.Driver","jdbc:mysql:///amdr?serverTimezone=GMT","root","wk7656265");
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(GoodsDao.class);
/**
* 解析mappers属性 使得注解和xml两种方式都能实现
* 通过XMLMapperBuilder解析完后的每个语句块儿都会封装为一个MappedStatement对象并存入Map<String,MappedStatement>中
* 存入到Configuration中,再由SqlSessionFactoryBuilder的build()方法,构建SqlSessionFactory会话工厂对象
*/
String resource = "mapper/GoodsMapper.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
mapperParser.parse();
sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration