Mybatis是支持定制化SQL、存储过程和高级映射的持久层框架。主要完成两件事:
- 封装JDBC的操作
- 利用反射完成Java类和SQL之间的转换
mybatis的主要目的就是管理执行SQL是参数的输入和输出,编写SQL和结果集的映射是mybatis的主要优点
mybatis中主要类和接口
- Configuration:将mybatis配置文件中的信息保存到该类中
- SqlSessionFactory:解析Configuration类中的配置信息,获取SqlSession
- SqlSession:负责和数据库交互,完成增删改查
- Executor:mybatis的调度核心,负责SQL的生成
- StatementHandler:封装了JDBC的statement操作
- ParameterHandler:负责完成JavaType到jdbcType的转换
- ResultSetHandler:负责完成结果集到Java Bean的转换
- MappedStatement:代表一个select|update|insert|delete元素
- SqlSource:根据传入的ParamterObject生成SQL
- BoundSql:包含SQL和参数信息
SqlSessionFactory和SqlSession源码
SqlSessionFactory的创建是mybatis的第一步,SqlSession完成数据库增删改查。我们先来看看二者的创建
首先创建SqlSessionFactoryBudiler对象,在调用builder方法读取mybatis配置文件,并创建SqlSessionFactory:
public class SqlSessionFactoryBuilder {
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
}
不管是调用SqlSessionFactoryBuilder哪个build重载方法,最后调用的都是上面的两种,这两种的区别只是采用不同的流读取配置文件,最后都会调用build(Configuration config)创建SqlSessionFactory接口的实现类对象
当创建SqlSessionFactory完成后下一步就是创建SqlSession:
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory