mybatis封装了jdbc操作数据库的代码,通过sqlsession来执行sql语句,那么首先来看看mybatis是怎么创建sqlsession。
mybatis没有托管给spring的时候,数据库的配置信息是在configuration.xml文件里边配置的 ,测试代码如下
1 Reader reader = Resources.getResourceAsReader("Configuration.xml");
Mybatis通过SqlSessionFactoryBuilder.build(Reader reader)方法创建一个SqlSessionFactory对象 build方法的参数就是刚才的reader对象,里边包含了配置文件的所有信息,build方法有很多重载方法
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
//委托XMLConfigBuilder来解析xml文件,并构建
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}
最后返回一个DefaultSqlSessionFactory对象,通过DefaultSqlSessionFactory的openSession()返回一个SqlSession对象
本程序源码为asp与acc编写,并没有花哨的界面与繁琐的功能,维护简单方便,只要你有一些点点asp的基础,二次开发易如反掌。 1.功能包括产品,新闻,留言簿,招聘,下载,...是大部分中小型的企业建站的首选。本程序是免费开源,只为大家学习之用。如果用于商业,版权问题概不负责。1.采用asp+access更加适合中小企业的网站模式。 2.网站页面div+css兼容目前所有主流浏览器,ie6+,Ch
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
final Environment environment = configuration.getEnvironment();
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
//通过事务工厂来产生一个事务
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//生成一个执行器(事务包含在执行器里)
final Executor executor = configuration.newExecutor(tx, execType);
//然后产生一个DefaultSqlSession
return new DefaultSqlSession(configuration, executor, autoCommit);
} catch (Exception e) {
//如果打开事务出错,则关闭它
closeTransaction(tx); // may have fetched a connection so lets call close()
throw ExceptionFactory.wrapException("Error opening session. Cause: " + e, e);
} finally {
//最后清空错误上下文
ErrorContext.instance().reset();
}
}
可以看到最后返回一个DefaultSqlSession即SqlSession对象,DefaultSqlSession中的selectOne(…) selectList(…)
selectMap(…) update(…)等方法就是真正执行要执行sql的方法
具体的执行由executor对象来执行
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = configuration.getMappedStatement(statement);
executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}









