Ibatis中,加载、分析配置及映射文件是在创建SqlMapper实例的时候进行的,另外对数据库的操作,也是在SqlMapper实例上调用方法来完成。创建SqlMapper的实例的方式是:
ISqlMapper mapper = Mapper.Instance();
//DomSqlMapBuilder builder = new DomSqlMapBuilder();
//ISqlMapper mapper = builder.Configure();
在第一次调用Mapper.Instance()的时候,由DomSqlMapBuilder对象解析SqlMap.config(默认路径和命名)文件来创建SqlMapper实例,然后会缓存该mapper对象,如果程序运行过程中,修改了映射文件,那么再调用Mapper.Instance()创建SqlMapper实例时,SqlMapper会被重新加载创建。相当于一个文件缓存依赖,这个文件缓存依赖由DomSqlMapBuilder.ConfigureAndWatch方法来实现。
IBatis.net的这个东西有个地方不好,默认是使用HttpContext作为xxx容器的。当非Web请求线程调用时,如Timer调用时会报如下错误:
ibatis.net:WebSessionStore: Could not obtain reference to HttpContext
这个问题可以在创建SQLMapper的时候指定:
添加名为MapperHelper的类,可以通过此类来获得SqlMapper实例
代码如下:
public class MapperHelper
{
private static volatile ISqlMapper _mapper;
private static readonly object obj = new object();
private static string SQL_MAP_CONFIG = "SqlMap.config";
protected static void Configure(object obj)
{
} public static ISqlMapper Instance(string sqlMapConfig = "")
{
if (string.IsNullOrEmpty(sqlMapConfig))
{
sqlMapConfig = SQL_MAP_CONFIG;
}
ConfigureHandler handler = new ConfigureHandler(Configure);
DomSqlMapBuilder builder = new DomSqlMapBuilder();
try
{
if (_mapper == null)
{
lock (obj)
{
if (_mapper == null)
{
_mapper = builder.ConfigureAndWatch(sqlMapConfig, handler);
if (HttpContext.Current == null)
{
_mapper.SessionStore = new HybridWebThreadSessionStore(_mapper.Id);
}
}
}
}
return _mapper;
}
catch (Exception e)
{
return null;
}
} }
参考:http://www.cnblogs.com/caoyc/category/873268.html