mybatis源码解析(三)SqlSession获取Mapper代理对象
·
1、SqlSession session = sqlSessionFactory.openSession(); // 获取SqlSession 对象
1)configuration.getDefaultExecutorType()获取默认的执行器类型,一共有三种,默认是SIMPLE
public enum ExecutorType {
SIMPLE, // 简单类型
REUSE, // 重用类型
BATCH // 批量处理类型
}
2)openSessionFromDataSource方法
SqlSession session = sqlSessionFactory.openSession();
// configuration.getDefaultExecutorType()获取默认的执行器类型
openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
// 创建事务
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
// 创建默认执行器SIMPLE
final Executor executor = configuration.newExecutor(tx, execType);
// 创建DefaultSqlSession对象
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
2)获取mapper接口代理对象
获取之前SqlSessionFactory初始化时保存的Mapper代理工厂,创建出mapper代理对象,调用栈
UserMapper mapper = session.getMapper(UserMapper.class);
configuration.getMapper(type, this);
mapperRegistry.getMapper(type, sqlSession);
// 获取mapper代理工厂
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
// mapper代理工厂创建mapper代理对象
mapperProxyFactory.newInstance(sqlSession);
newInstance(mapperProxy);
(T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
3) 根据mapper代理对象调用mapper接口方法时,就会执行invocationHandler中的invoke方法,执行sql并解析结果返回。
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)