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执行过程中的事务边界,确保数据的一致性。

相关推荐
想不明白的过度思考者2 小时前
Spring Boot 配置文件深度解析
java·spring boot·后端
cike_y7 小时前
Mybatis之解析配置优化
java·开发语言·tomcat·mybatis·安全开发
QQ142207844910 小时前
没有这个数据库账户,难道受到了sql注入式攻击?
数据库·sql
隔壁阿布都10 小时前
使用LangChain4j +Springboot 实现大模型与向量化数据库协同回答
人工智能·spring boot·后端
勇往直前plus10 小时前
MyBatis/MyBatis-Plus类型转换器深度解析:从基础原理到自定义实践
数据库·oracle·mybatis
cyhysr10 小时前
sql将表字段不相关的内容关联到一起
数据库·sql
古城小栈11 小时前
Spring Boot 数据持久化:MyBatis-Plus 分库分表实战指南
spring boot·后端·mybatis
无名-CODING11 小时前
SQL 注入指南
sql·mybatis
悟能不能悟11 小时前
springboot全局异常
大数据·hive·spring boot
+VX:Fegn089512 小时前
计算机毕业设计|基于springboot + vue宠物寄养系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计·宠物