目录
1、解析xml文件
根据配置的mapperLocations路径,找到路径下的所有xml文件进行解析,通过xml中的<mapper>标签与dao接口进行一对一映射。
<mapper namespace="com.example.xxx.dao.UserDao">
解析xml中的<select|insert|update|delete>标签,通过id与dao接口中的方法名进行一对一映射。
// dao接口
public List<User> search();
// xml标签
<select id="search" resultType="com.example.xxx.entity.User">
2、封装MappedStatement
将每个SQL标签封装成SqlSource对象,SqlSource又分为动态SQL和静态SQL。其中,静态SQL包含是String类型的sql语句;而动态SQL则是由一个个SqlNode
组成。
XML中的每个标签都会生成一个MappedStatement对象,每个MappedStatement对象中,主要包含id和SqlSource,其中:
- id:namespace + 方法名。用于业务调用dao方法时,找到对应的MappedStatement对象。
- SqlSource:当前标签对应的SqlSource对象。用于具体SQL执行。
然后将创建好的MappedStatement对象添加到Configuration中。
3、解析dao接口
解析@MapperScan配置的dao扫描路径,将路径下的dao接口全部注册成Java Bean,并将Bean设置为MapperFactoryBean。
MapperFactoryBean实现了FactoryBean(工厂Bean),在通过@Autowired注入dao接口对象时,实际上获取的是工厂Bean中的getObject()返回值。该方法通过JDK动态代理,返回一个dao接口的代理对象MapperProxy,当在业务系统中调用dao接口方法时,就会调用MapperProxy对象的invoke()方法。
4、调用dao接口
在业务代码中,在调用dao接口方法时,会执行MapperProxy代理对象中的invoke方法。该方法实际会去调用SqlSession中的相应方法,拿<select>标签举例:
public class DefaultSqlSession implements SqlSession {
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
return executor.query(ms,
wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
}
}
}
- 通过statement(全限定类名 + 方法名)获取Configuration中存储的MappedStatement;
- 通过执行器Executor解析SqlSource并执行sql,返回sql执行结果。
以上内容为个人学习总结,仅供学习参考,如有问题,欢迎在评论区指出,谢谢!