MyBatis3源代码阅读(一)
文章目录
mybatis介绍以及框架源码的学习目标
MyBatis是当前最流行的java持久层框架之一,其通过XML配置的方式消除了绝大部分JDBC重复代码以及参数的设置,结果集的映射。虽然mybatis是最为流行的持久层框架之一,但是相比其他开源框架比如spring/netty的源码来说,其注释相对而言显得比较少。为了更好地学习和理解mybatis背后的设计思路,作为高级开发人员,有必要深入研究了解优秀框架的源码,以便更好的借鉴其思想。同时,框架作为设计模式的主要应用场景,通过研究优秀框架的源码,可以更好的领会设计模式的精髓。学习框架源码和学习框架本身不同,我们不仅要首先比较细致完整的熟悉框架提供的每个特性,还要理解框架本身的初始化过程等,除此之外,更重要的是,我们不能泛泛的快速浏览哪个功能是通过哪个类或者接口实现和封装的,对于核心特性和初始化过程的实现,我们应该达到下列目标:
- 对于核心特性和内部功能,具体是如何实现的,采用什么数据结构,边研究边思考这么做是否合理,或者不合理,尤其是很多的特性和功能的调用频率是很低的,或者很多集合中包含的元素数量在99%以上的情况下都是1,这种情况下很多设计决定并不需要特别去选择或者适合于大数据量或者高并发的复杂实现。对于很多内部的数据结构和辅助方法,不仅需要知道其功能本身,还需要知道他们在上下文中发挥的作用。
- 对于核心特性和内部功能,具体实现采用了哪些设计模式,使用这个设计模式的合理性;
- 绝大部分框架都被设计为可扩展的,mybatis也不例外,它提供了很多的扩展点,比如最常用的插件,语言驱动器,执行器,对象工厂,对象包装器工厂等等都可以扩展,所以,我们应该知道如有必要的话,如何按照要求进行扩展以满足自己的需求。
实例整体图

2.从一个实例开始
@Slf4j
public class HelloWorld {
public static void main(String[] args) {
String resource = "config.xml”;//配置文件
Reader reader;
try {
//2.读取配置文件
reader = Resources.getResourceAsReader(resource);//2.读取配置文件
//3.构建SqlSessionFactory
SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
//4.创建一个SqlSession
SqlSession sqlSession = sqlMapper.openSession();
try {
//5.执行一个Query
User user = sqlSession.selectOne("com.blueheart.mybatis.mapper.UserMapper.getUser", 1);
log.error("user id={},name={}",user.getId(),user.getName());
}finally {
//6.结束关闭
sqlSession.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}从上述代码过程中,我们看看这个过程涉及几个对象及相关的方法
0.config.xml
1.Resources.getResourceAsReader(resource);
2.SqlSessionFactory
3.SqlSessionFactoryBuilder
4.SqlSession配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>分析代码的这一行,从一个资源返回一个Reader(字符流)
//2.读取配置文件
reader = Resources.getResourceAsReader(resource);//2.读取配置文件Resources.class
这个类是读取资源类,具体完成将xml文件加载生成一个Reader,这里我就有一个疑问,为什么大部分的框架都要自己弄一个Resource类呢?加载一个文件或URL资源都是比较简单的?真是这样子吗?我们来看看Resource.class的源代码:
/**
* A class to simplify access to resources through the classloader.
* 一个简单的通过类加载器访问资源的类
*
* @author Clinton Begin
*/
public class Resources {
//类加载器包装类?为什么,我们接后面再看
private static ClassLoaderWrapper classLoaderWrapper = new ClassLoaderWrapper();
/**
* Charset to use when calling getResourceAsReader.
* null means use the system default.
* 字符集,默认使用系统的,考虑得比较周全,一般我们都没有考虑或直接写死
*/
private static Charset charset;
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
//把返回的过程委托给了classLoaderWrapper
URL url = classLoaderWrapper.getResourceAsURL(resource, loader);
if (url == null) {
throw new IOException("Could not find resource " + resource);
}
return url;
}
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
//把返回的过程委托给了classLoaderWrapper
InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
if (in == null) {
throw new IOException("Could not find resource " + resource);
}
return in;
}
/**
* Returns a resource on the classpath as a Properties object
* 得到一个资源的Properties对象,资源是.properties文件
* @param resource The resource to find
* @return The resource
* @throws java.io.IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(String resource) throws IOException {
Properties props = new Properties();
try (InputStream in = getResourceAsStream(resource)) {
props.load(in);
}
return props;
}
public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
Properties props = new Properties();
try (InputStream in = getResourceAsStream(loader, resource)) {
props.load(in);
}
return props;
}
public static Reader getResourceAsReader(String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(resource));
} else {
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(loader, resource));
} else {
reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
}
return reader;
}
public static File getResourceAsFile(String resource) throws IOException {
return new File(getResourceURL(resource).getFile());
}
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
return new File(getResourceURL(loader, resource).getFile());
}这个资源类里最重要的只有几个方法,就是实际执行的方法,这里面有涉及另外一个类ClassLoaderWrapper ,看上去所有这些实际加载都是
我们再来看看ClassLoaderWrapper是如何去实际加载资源的
/**
* A class to wrap access to multiple class loaders making them work as one
* 一个包装访问多个类加载器使它看起来像在访问一个一样加载资源
*
* @author Clinton Begin
*/
public class ClassLoaderWrapper {
ClassLoader defaultClassLoader;
ClassLoader systemClassLoader;
ClassLoaderWrapper() {
try {
systemClassLoader = ClassLoader.getSystemClassLoader();
} catch (SecurityException ignored) {
// AccessControlException on Google App Engine
}
}
…
//核心方法之一,其它一样
InputStream getResourceAsStream(String resource, ClassLoader[] classLoader) {
for (ClassLoader cl : classLoader) {
if (null != cl) {
// try to find the resource as passed
InputStream returnValue = cl.getResourceAsStream(resource);
// now, some class loaders want this leading "/", so we'll add it and try again if we didn't find the resource
if (null == returnValue) {
returnValue = cl.getResourceAsStream("/" + resource);
}
if (null != returnValue) {
return returnValue;
}
}
}
return null;
}
//核心方法
ClassLoader[] getClassLoaders(ClassLoader classLoader) {
return new ClassLoader[]{
classLoader,
defaultClassLoader,
Thread.currentThread().getContextClassLoader(),
getClass().getClassLoader(),
systemClassLoader};
}
}这个类做了一件什么事情呢?就是按顺序找到一个合适的类加载器,去加载相应的资源。最核心的方法就是最后一个ClassLoader[] getClassLoaders(ClassLoader classLoader),它返回自己顺序的类加载器列表,一般情况下classLoader和defaultClassLoader都为null,所以使用最多的就是 Thread.currentThread().getContextClassLoader()这个类加载器,这里涉及一个基础知识点JVM类加载过程模模型。
总结
- 框架的资源加载要比一般的使用复杂,所以需要有一种机制能正确的加载,首先要解决的就是从不同的classLoader加载的问题,以保证能下确找到资源
- 可以返回不同的流,如字节流、字符流、Properties或URL
- 转换的过程中要尽可以能考虑全面,文件就有编码,所以可以设定指定的编码格式
附加知识
- Java默认是有三个ClassLoader,按层次关系从上到下依次是:
* - Bootstarp ClassLoader
- Ext ClassLoader
- System ClassLoader
* - “双亲委托”
- 所谓“双亲委托”就是当加载一个类的时候会先委托给父类加载器去加载,当父类加载器无法加载的时候再尝试自己去加载,所以整个类的加载是“自上而下”的,如果都没有加载到则抛出ClassNotFoundException异常。
* - 上面提到Bootstarp ClassLoader是最顶层的类加载器,实际上Ext ClassLoader和System ClassLoader就是一开始被它加载的。
* - ClassLoader称为扩展类加载器,负责加载Java的扩展类库,默认加载JAVA_HOME/jre/lib/ext/目下的所有jar(包括自己手动放进去的jar包)。
* - System ClassLoader叫做系统类加载器,负责加载应用程序classpath目录下的所有jar和class文件,包括我们平时运行jar包指定cp参数下的jar包。
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论