SpringBoot里MyBatis - SQL执行过程

SpringBoot整合MyBatis的环境中,执行SQL的过程可以分为以下几个步骤:

配置数据源(DataSource):
SpringBoot通过application.propertiesapplication.yml配置数据库连接信息,创建并配置DataSource

配置SqlSessionFactory:
使用org.mybatis.spring.SqlSessionFactoryBean来构建SqlSessionFactory

java 复制代码
   import org.apache.ibatis.session.SqlSessionFactory;
   import org.mybatis.spring.SqlSessionFactoryBean;
   import org.mybatis.spring.annotation.MapperScan;
   import org.springframework.beans.factory.annotation.Autowired;
   import org.springframework.context.annotation.Bean;
   import org.springframework.context.annotation.Configuration;
   import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
   import org.springframework.jdbc.datasource.DataSourceTransactionManager;

   @Configuration
   @MapperScan(basePackages = "com.example.myapp.mapper") // 替换为你的Mapper接口所在的包名
   public class MybatisConfig {

       @Autowired
       private DataSource dataSource;

       @Bean
       public SqlSessionFactory sqlSessionFactory() throws Exception {
           SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
           factoryBean.setDataSource(dataSource);
   
           // 设置MyBatis全局配置文件的位置(如果有的话)
           factoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml"));

           // 设置Mapper XML文件的位置
           factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));

           return factoryBean.getObject();
       }

       @Bean
       public DataSourceTransactionManager transactionManager() {
           return new DataSourceTransactionManager(dataSource);
       }
   }

注入Mapper接口:
Mapper接口@Component或者@Repository注解的方式声明为一个Spring Bean
或者在配置类中使用@MapperScan注解指定扫描包含Mapper接口的包路径,这样Spring容器就能自动发现并创建Mapper接口的代理对象。。

获取Mapper实例并执行方法:
在业务层Service中,通过@Autowired注解注入Mapper接口。
当调用Mapper接口的方法时,由于Spring已经为其生成了动态代理对象,所以实际上是在执行代理对象的方法。
代理方法内部会根据Mapper接口的方法签名和对应的XML映射文件或注解找到SQL语句。

执行SQL:
MyBatis会通过SqlSession执行SQL语句,它是由SqlSessionFactory创建的。
SQL执行过程中,MyBatis会利用StatementHandler对SQL进行预编译处理、通过ParameterHandler设置参数。Executor(执行器)负责执行具体的SQL操作,包括查询、插入、更新和删除等,并可能涉及缓存策略的使用。

结果映射与返回:
执行完SQL后,MyBatis会通过ResultHandlerResultMap将结果集转换成Java对象,并返回给调用者

事务管理:
在Spring Boot中,可以通过@Transactional注解实现声明式事务管理,Spring会自动处理SQL执行过程中的事务边界,确保数据的一致性。

相关推荐
初次攀爬者11 小时前
RocketMQ在Spring Boot上的基础使用
java·spring boot·rocketmq
花花无缺11 小时前
搞懂@Autowired 与@Resuorce
java·spring boot·后端
Derek_Smart13 小时前
从一次 OOM 事故说起:打造生产级的 JVM 健康检查组件
java·jvm·spring boot
Nyarlathotep011319 小时前
SpringBoot Starter的用法以及原理
java·spring boot
dkbnull2 天前
深入理解Spring两大特性:IoC和AOP
spring boot
洋洋技术笔记2 天前
Spring Boot条件注解详解
java·spring boot
洋洋技术笔记3 天前
Spring Boot配置管理最佳实践
spring boot
用户8307196840823 天前
Spring Boot 项目中日期处理的最佳实践
java·spring boot
大道至简Edward4 天前
Spring Boot 2.7 + JDK 8 升级到 Spring Boot 3.x + JDK 17 完整指南
spring boot·后端
洋洋技术笔记4 天前
Spring Boot启动流程解析
spring boot·后端