Mybatis的初始化过程
1 mybatis使用代码
public class MyBatisMain {
public static void main(String[] args) {
// 第一阶段:MyBatis的初始化阶段,配置各项属性
String resource = "conf/mapperTest.xml";
// 得到配置文件的输入流
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory =
new SqlSessionFactoryBuilder().build(inputStream);
//第二阶段发出数据库请求操作
try (SqlSession session = sqlSessionFactory.openSession()) {
Student student = session.selectOne("mapper/mapperSql.getUserById", 2);
System.out.println(student.toString());
}
}
}
主体代码分为两部分:
-
分是通过配置文件将mybatis中的各个内置注册列表填充,然后获取SqlsessionFactory。
-
执行与数据库相关的操作,包括sql语句转换,返回值处理等。
2 mybatis的流程解析
创建XMLConfigBuilder --> 用其解析XML文件获取Config --> SqlSessionFactory使用Config获取sqlSession
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
public SqlSessionFactory build(InputStream inputStream, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
inputStream.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
/**
* 根据配置信息建造一个SqlSessionFactory对象
* @param config 配置信息
* @return SqlSessionFactory对象
*/
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}