网站首页 > 精选文章 / 正文
弱小和无知并不是生存的障碍,傲慢才是。
---- ---- 面试者
总结
在MyBatis与Springboot整合之后,MyBatis的启动同样是依托SpringBoot的自动装载。主要涉及两个流程,其一是Mapper接口的注册过程,在申明@MapperScan()注解时,在beanDefinitions注册的过程中会触发Mapper的注册,在bean实例化时,Mapper接口会被实例化为一个MapperProxy代理类,其二是mapper.xml文件的加载,在自动装载MybatisAutoConfiguration时,会触发SqlSessionFactory的注入加载,期间会解析xml文件,并且将申明的sql与id以kv形式缓存。
在调用mapper接口时,会通过代理类MapperProxy进行调用,基于调用的接口名称找到要自信的SQL,然后层层包装调用,最后交由Druid进行执行(Druid持有连接,Mybatis包装到最后的PreparedStatement之后,交由Druid提交执行)。
MyBatis启动
Mapper接口注入
// 我们在Application.class中添加的@MapperScan()注解,包含了一个@Import({MapperScannerRegistrar.class})
// 该类实现了ImportBeanDefinitionRegistrar接口,会自动调用registerBeanDefinitions方法进行注册bean
void registerBeanDefinitions(AnnotationMetadata annoMeta, AnnotationAttributes annoAttrs, BeanDefinitionRegistry registry, String beanName) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
// ......
// 这里自注册了MapperScannerConfigurer,是一个bean后置处理器类,
// 初始化时会自动调用这个类的postProcessBeanDefinitionRegistry方法
registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
}
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
// ......
scanner.registerFilters();
// 这里进行扫描,直接调用了spring自带的扫描逻辑方法,并完成bean的扫描;
// 然后修改Mapper接口,将beanClass设置为MapperFactoryBean工厂
// 当业务层bean依赖了mapper,进行依赖初始化时,会基于MapperFactoryBean把依赖的mapper初始化一个代理实例
scanner.scan(StringUtils.tokenizeToStringArray(this.basePackage, ",; \t\n"));
}
Mapper.xml文件扫描
// 通过自动装载逻辑,初始化MybatisAutoConfiguration时,由于SqlSessionFactory添加了@bean
// 在初始化SqlSessionFactory时,便会加载xml文件
// SqlSessionFactoryBean进行实例化时,调用了afterPropertiesSet,
// 然后对存储在mapperLocations的mapper文件进行解析,生成MappedStatement,结合id以kv形式存在了Configuration对象mappedStatements属性中
@Bean
@ConditionalOnMissingBean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
// 加载xml文件
Resource[] mapperLocations = this.properties.resolveMapperLocations();
if (!ObjectUtils.isEmpty(mapperLocations)) {
factory.setMapperLocations(mapperLocations);
}
}
MyBatis接口调用
// mppaer接口调用时,会初始化PlainMethodInvoker,构造函数里会根据接口名称去Configuration里找到对应的sql;
// 然后调用到invoke方法,MapperMethod示例里边两个属性,一个SqlCommand 一个MethodSignature
// SqlCommand包括接口名称和执行类型是select还是update等
// MethodSignature方法签名,包含接口返回类型和参数
private static class PlainMethodInvoker implements MapperMethodInvoker {
private final MapperMethod mapperMethod;
public PlainMethodInvoker(MapperMethod mapperMethod) {
this.mapperMethod = mapperMethod;
}
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
return this.mapperMethod.execute(sqlSession, args);
}
}
// 进行sql类型判定,这里以Select为例
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (this.command.getType()) {
case INSERT:
Object param = this.method.convertArgsToSqlCommandParam(args);
result = this.rowCountResult(sqlSession.insert(this.command.getName(), param));
break;
case UPDATE:
Object param = this.method.convertArgsToSqlCommandParam(args);
result = this.rowCountResult(sqlSession.update(this.command.getName(), param));
break;
case DELETE:
Object param = this.method.convertArgsToSqlCommandParam(args);
result = this.rowCountResult(sqlSession.delete(this.command.getName(), param));
break;
case SELECT:
if (this.method.returnsVoid() && this.method.hasResultHandler()) {
this.executeWithResultHandler(sqlSession, args);
result = null;
} else if (this.method.returnsMany()) {
result = this.executeForMany(sqlSession, args);
} else if (this.method.returnsMap()) {
result = this.executeForMap(sqlSession, args);
} else if (this.method.returnsCursor()) {
result = this.executeForCursor(sqlSession, args);
} else {
Object param = this.method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(this.command.getName(), param);
if (this.method.returnsOptional() && (result == null || !this.method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + this.command.getName());
}
if (result == null && this.method.getReturnType().isPrimitive() && !this.method.returnsVoid()) {
throw new BindingException("Mapper method '" + this.command.getName() + "' attempted to return null from a method with a primitive return type (" + this.method.getReturnType() + ").");
} else {
return result;
}
}
// sqlsession持有defaultsqlsession,进一步执行查询
private List selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
List var6;
try {
// 再次从Configuration中,找出接口对应的MappedStatement
MappedStatement ms = this.configuration.getMappedStatement(statement);
this.dirty |= ms.isDirtySelect();
// 交由执行器执行
var6 = this.executor.query(ms, this.wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
return var6;
}
// 调用PreparedStatementHandler 的query方法,期间会构造statement = DruidPooledPreparedStatement
// 由连接池druid包装的PreparedStatement
public List query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement)statement;
// 这里边执行的就是jdbc那一套了
ps.execute();
// 处理返回结果
return this.resultSetHandler.handleResultSets(ps);
}
举杯邀明月,对影成三人。
Tags:mybatis
猜你喜欢
- 2025-04-06 mybatis手把手教学,希望大家能拿下它
- 2025-04-06 15 种超赞的 MyBatis 写法(mybatis ne)
- 2025-04-06 mybatis-plus保姆级入门教程,手把手教你轻松实现增删改查
- 2025-04-06 如何深度理解mybatis?(如何深度理解标的分配)
- 2025-04-06 Mybatis框架(mybatis框架的主要作用)
- 2025-04-06 深入详解Mybatis的架构原理与6大核心流程
- 2025-04-06 「Java知识」Mybatis的特性详解——动态SQL,拿走不谢
- 2025-04-06 mybatisplus的介绍和基本使用(mybatis_plus)
- 2025-04-06 MyBatis where、set、trim(set是什么意思)