一、一句话先给结论(先有整体感)
Mapper 能找到实体和数据库,靠的是这 4 件事:
-
Mapper 接口被 Spring 扫描成 Bean
-
Mapper 接口 ↔ XML 的 namespace / 方法名 对应
-
SQL 执行结果 ↔ 实体字段 映射
-
DataSource + SqlSessionFactory 决定"连哪个数据库"
二、Mapper 是怎么"被 Spring 发现"的?
1️⃣ Mapper 本质是什么?
public interface UserInfoMapper {
String querySystemUser();
}
注意一句话:
Mapper 接口没有实现类,但运行时却能调用
为什么?
2️⃣ @MapperScan 做了什么?
在 Spring Boot 启动类里(或配置类):
@SpringBootApplication
@MapperScan("。。。。。")
public class Application {
}
它做了三件事:
-
扫描包
-
发现所有 Mapper 接口
-
给每个接口生成一个"动态代理对象"
这个代理对象,才是真正被注入的 Bean。
@Autowired
private UserInfoMapper userInfoMapper; // 注入的是代理对象
三、Mapper 是怎么"找到数据库"的?
1️⃣ 数据库连接是谁管的?
不是 Mapper。
是 DataSource。
spring:
datasource:
url: jdbc:postgresql://localhost:5432/xxx
username: postgres
password: ***
Spring Boot 自动帮你创建:
DataSource
↓
SqlSessionFactory
↓
SqlSession
所有 Mapper 都共用这个 SqlSessionFactory
2️⃣ 所以 Mapper 干的事情其实只有一件:
"拿着 SQL → 通过 SqlSession → 用 DataSource 执行"
四、Mapper 方法是怎么找到 XML 里的 SQL 的?
| Mapper 接口 | XML |
|---|---|
| 全限定名 | namespace |
| 方法名 | select / update / insert 的 id |