mybatis_helloworld(2)_源码(一)

2014-11-24 08:22:29 · 作者: · 浏览: 9
在helloworld(1)中,分析了insert一条数据的流程,现在分析下 源码
[java]
public static void main(String args[]) throws IOException {
String resource = "com/test/configuration.xml";//获得xml(Mybatis) 数据库连接的连接
Reader reader = Resources.getResourceAsReader(resource);//读取里面的文件
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
.build(reader);//创建session工厂
SqlSession session = sessionFactory.openSession();//打开session
new Test1().insert(session);
}
1. XML文件资源的获取
a)包路径:org.apache.ibatis.io
b)Resources类:定义了一系列的静态方法,用于获取资源(ClassLoader,URL,InputStream,Read,File,Properties,Charset)
c)我们用到的getResourceAsReader,getResourceAsStream方法
[java]

public static Reader getResourceAsReader(String resource)

throws IOException
{
Reader reader;

· //利用InputStream构造Reader

if(charset == null)
reader = new InputStreamReader(getResourceAsStream(resource));
else
reader = new InputStreamReader(getResourceAsStream(resource), charset);
return reader;
}

public static InputStream getResourceAsStream(String resource)

throws IOException
{

//调用重载方法

return getResourceAsStream(null, resource);
}

public static InputStream getResourceAsStream(ClassLoader loader, String resource)

throws IOException
{

//调用ClassLoaderWrapper类的方法,利用ClassLoader获取资源

InputStream in = classLoaderWrapper.getResourceAsStream(resource, loader);
if(in == null)
throw new IOException((new StringBuilder()).append("Could not find resource ").append(resource).toString());
else
return in;
}

d)ClassLoaderWrapper类:封装了一个ClassLoader数组,通过ClassLoader获取资源
e)我们用到的getResourceAsStream,getClassLoaders方法
[java]
public InputStream getResourceAsStream(String resource, ClassLoader classLoader)
{
return getResourceAsStream(resource, getClassLoaders(classLoader));
}
ClassLoader[] getClassLoaders(ClassLoader classLoader)
{
return (new ClassLoader[] { //构建新的ClassLoader列表,包含用户创建及默认
classLoader, defaultClassLoader, Thread.currentThread().getContextClassLoader(), getClass().getClassLoader(), systemClassLoader});
}
InputStream getResourceAsStream(String resource, ClassLoader classLoader[])
{
ClassLoader arr$[] = classLoader;
int len$ = arr$.length;
for(int i$ = 0; i$ < len$; i$++) //遍历ClassLoader数组,当某一个Loader成功构建资源则返回
{
ClassLoader cl = arr$[i$];
if(null == cl)
continue;
InputStream returnValue = cl.getResourceAsStream(resource);
if(null == returnValue)
returnValue = cl.getResourceAsStream((new StringBuilder()).append("/").append(resource).toString());
if(null != returnValue)
return returnValue;
}
return null;
}
2. 构建SqlSessionFactory,初始化资源
a) SqlSessionFactory接口介绍
[java]
public interface SqlSessionFactory
{
//定义了一系列获取Session的方法,获取Configuration的方法
public abstract SqlSession openSession();
public abstract SqlSession openSession(boolean flag);
public abstract SqlSession openSession(