今天说说MyBatis3和iBatis2。大家现在正常的项目都应该使用MyBatis3了。动态代理的Mapper机制,只要考虑3个要素(xxxMapper.java, xxxMapper.xml, xxxPojo.java),完全面向对象的开发方式,用起来相当爽。更重要的是,还有Mybatis Generator工具可以自动生成DAO层。
在MyBatis3之前还有iBatis2,有些比较年轻的程序员可能都没有用过这个东西。有些比较老的工程可能还在用,我之前在某银行的时候就用iBatis2,写到DAO层就想睡觉。吐槽下iBatis2开发恶心的地方。
- 表的映射配置,表很大,如果有20个字段。都得逐个copy(调试的时候就怕哪个字段错了)
- sql的id是随便起名字的,表与表之前也没有严格的sql范围划分。
- 写调用代码时是面向过程的,queryForObject出来的对象需要强制转换。
- java代码中各种硬编码
- 大家为了当下省事,在调用时常常使用map进,map出。特别难看
iBatis2的示意代码
public Student findStudentById(int studentId) {
SqlMapClient sqlMapClient = MyBatisUtil.getSqlSqlMapClient();
SqlMapSession sqlMapSession = sqlMapClient.openSession();
try {
Student student = (Student) sqlMapSession.queryForObject("student.queryByPrimaryKey", studentId);
} finally {
sqlMapSession.close();
}
}
MyBatis的示意代码
public Student findStudentById(int studentId) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = studentMapper.queryByPrimaryKey(studentId);
return student;
} finally {
sqlSession.close();
}
}
对比之后会发现MyBatis是面向对象的,使用Mapper机制,可以使得表之前的sql有一定的隔离。入参和出餐都可以尽量使用面向对象的方式。硬编码也没有了。
苦逼程序员在代码还得写,ibatis2还得用,怎么办?能不能在ibatis2基础上做一个适配层,使得我们在业务代码中可以像使用MyBatis3一样面向对象的方式去使用ibatis2呢?
答案当然是可以,要不然我也不会写这文章了。不仅可以像MyBatis3一样调用,连MyBatis Generator的自动生成器也可以拿过来改吧改吧适配iBatis2。下面我们来详细说说。
要干此事的前提是,要先了解MyBatis3在Mapper映射部分的原理。
MyBatis3 源代码分析
Mapper机制从流程上分为3个步骤
1.启动时做初始化动作
2.运行时使用getMapper方法生成动态代理
3.调用sql执行过程(这部分的核型实际与iBatis差不多)
Mapper机制初始化
系统启动首先会初始化Configuration,我们从Configuration的初始化位置开始看。请先找到XMLConfigBuilder类。
public Configuration parse() {
if (parsed) {
throw new BuilderException("Each XMLConfigBuilder can only be used once.");
}
parsed = true;
parseConfiguration(parser.evalNode("/configuration"));
return configuration;
}
这段方法,是xml解析过程。重点关注parseConfiguration。
private void parseConfiguration(XNode root) {
try {
// 此处省略部分代码
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
继续跟进mapperElement
private void mapperElement(XNode parent) throws Exception {
if (parent != null) {
for (XNode child : parent.getChildren()) {
// 此处省略部分代码
configuration.addMapper(mapperInterface);
} else {
throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
}
}
}
}
}
继续跟进configuration.addMapper(mapperInterface);一路可以跟进到MapperRegistry类
public void addMappers(String packageName) {
addMappers(packageName, Object.class);
}
这个方法是要加载某个包下面的所有xxxMapper.java(也就是我们所写的比如UserMapper.java,这种DAO行为接口),为后续运行时生成动态代理类做准备。(我们在业务代码中常写的sqlSession.getMapper方法,就是在生成动态代理)
public class MapperRegistry {
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
boolean loadCompleted = false;
try {
// knownMappers<Mapper接口类型, Mapper代理的工场对象>
// 初始化时,会把这些东西缓存起来。为后续生成动态代理做准备。
knownMappers.put(type, new MapperProxyFactory<T>(type));
MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
parser.parse();
loadCompleted = true;
} finally {
if (!loadCompleted) {
knownMappers.remove(type);
}
}
}
}
}
关注下knownMappers,这里面的key和value分别是<Mapper接口类型, Mapper代理的工场对象>
初始化时,会把这些东西缓存起来。为后续生成动态代理做准备。
使用getMapper方法生成动态代理
还是在MapperRegistry类中,调用getMapper方法生成动态代理类。关于动态代理不太熟悉的同学,可以相关设计模式,这个模式非常重要。
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
// 生成动态代理
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
再来追踪下MapperProxyFactory,我把其中不太重要的部分去掉了
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
// 去掉了一些不太重要的部分代码
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
// 实际使用了JDK的动态代理,接口类型就是初始化时候放进knownMappers中的某一个。
// 具体类型是在getMapper的时候传入的。
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
实际使用了JDK的动态代理,接口类型就是初始化时候放进knownMappers中的某一个。具体类型是在getMapper的时候传入的。具体我们再回顾下上面那个MyBatis的调用案例。
MyBatis的示意代码
public Student findStudentById(int studentId) {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
try {
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
Student student = studentMapper.queryByPrimaryKey(studentId);
return student;
} finally {
sqlSession.close();
}
}
从这边可以看到。在调用getMapper时,会传入StudentMapper接口的类型。MyBatis会为这个接口生成动态代理类。下面我们看看这个动态代理实际执行了什么操作。找到MapperProxy类
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
// 重点关注这个invoke方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 去掉了一些不太重要的部分代码
final MapperMethod mapperMethod = cachedMapperMethod(method);// 这边先看看缓存
return mapperMethod.execute(sqlSession, args);
}
// 去掉了一些不太重要的部分代码
}
在业务代码中调用任何一个sql方法,比如selectByPrimaryKey()都会来到这个invoke方法中。我们继续追踪mapperMethod.execute方法
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
case INSERT: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
break;
}
case UPDATE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
break;
}
case DELETE: {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
break;
}
case SELECT:
if (method.returnsVoid() && method.hasResultHandler()) {
executeWithResultHandler(sqlSession, args);
result = null;
} else if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
result = executeForMap(sqlSession, args);
} else if (method.returnsCursor()) {
result = executeForCursor(sqlSession, args);
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(command.getName(), param);
}
break;
case FLUSH:
result = sqlSession.flushStatements();
break;
default:
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName()
+ " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ").");
}
return result;
}
看到上面这个方法,大家应该会明白了。到这边,所有的方法都会根据command.getType(),分化为insert,update,delete,select这4个元操作。
接下来的调用代码就不再这边继续分析了。感兴趣的同学可以继续更进。
到此,我们总结下,适配iBatis2的关键在与MapperMethod.execute这个方法。只需要在这里面实现增删改查4种元操作的时候,调用上iBatis2对应的4中元处理操作,这适配器不就对接上了么。
我们需要新建6个关键的类。分别是:
第一部分:MapperMethod,MapperProxy,MapperProxyFactory,MapperRegistry。这4个类基本是从MyBatis3中直接照搬过来。连类名都一模一样。
第二部分:SqlSession,SqlSessionDefault。这2个类是我们对iBatis2中SqlMapClient, SqlMapSession所做的适配器。这边完全使用了适配器模式。
好,我们先来看看SqlSession。
public interface SqlSession extends SqlMapClient, SqlMapSession {
<T> T getMapper(Class<T> type); // 模式MyBatis3中的getMapper方法
SqlMapExecutorDelegate getDelegate();// 是一个执行器,ibatis2需要用到
}
一共2个行为:
1.getMapper,模式MyBatis3中的getMapper方法
2.getDelegate,是一个执行器,ibatis2需要用到
然后看下SqlSession的实现类SqlSessionDefault
public class SqlSessionDefault implements SqlSession {
private SqlMapClient sqlMapClient; // 持有目标类的执行器
private MapperRegistry mapperRegistry;
private SqlMapExecutorDelegate delegate;
// 本地线程做缓存
private ThreadLocal<SqlMapSession> localSqlMapSession = new ThreadLocal<>();
public SqlSessionDefault(SqlMapClient sqlMapClient, MapperRegistry mapperRegistry) {
this.sqlMapClient = sqlMapClient;
this.mapperRegistry = mapperRegistry;
this.delegate = ((ExtendedSqlMapClient) this.sqlMapClient).getDelegate();
}
@Override
public SqlMapSession openSession() {
return sqlMapClient.openSession();
}
@Override
public SqlMapSession openSession(Connection conn) {
return sqlMapClient.openSession(conn);
}
@Override
public SqlMapSession getSession() {
return this.getLocalSqlMapSession();
}
@Override
public void flushDataCache() {
delegate.flushDataCache();
}
@Override
public void flushDataCache(String cacheId) {
delegate.flushDataCache(cacheId);
}
@Override
public Object insert(String id, Object parameterObject) throws SQLException {
return this.getLocalSqlMapSession().insert(id, parameterObject);
}
@Override
public Object insert(String id) throws SQLException {
return this.getLocalSqlMapSession().insert(id);
}
@Override
public int update(String id, Object parameterObject) throws SQLException {
return this.getLocalSqlMapSession().update(id, parameterObject);
}
@Override
public int update(String id) throws SQLException {
return this.getLocalSqlMapSession().update(id);
}
@Override
public int delete(String id, Object parameterObject) throws SQLException {
return this.getLocalSqlMapSession().delete(id, parameterObject);
}
@Override
public int delete(String id) throws SQLException {
return this.getLocalSqlMapSession().delete(id);
}
@Override
public Object queryForObject(String id, Object parameterObject) throws SQLException {
return this.getLocalSqlMapSession().queryForObject(id, parameterObject);
}
@Override
public Object queryForObject(String id) throws SQLException {
return this.getLocalSqlMapSession().queryForObject(id);
}
@Override
public Object queryForObject(String id, Object parameterObject, Object resultObject) throws SQLException {
return this.getLocalSqlMapSession().queryForObject(id, parameterObject, resultObject);
}
@Override
public List queryForList(String id, Object parameterObject) throws SQLException {
return this.getLocalSqlMapSession().queryForList(id, parameterObject);
}
@Override
public List queryForList(String id) throws SQLException {
return this.getLocalSqlMapSession().queryForList(id);
}
@Override
public List queryForList(String id, Object parameterObject, int skip, int max) throws SQLException {
return this.getLocalSqlMapSession().queryForList(id, parameterObject, skip, max);
}
@Override
public List queryForList(String id, int skip, int max) throws SQLException {
return this.getLocalSqlMapSession().queryForList(id, skip, max);
}
@Override
public void queryWithRowHandler(String id, Object parameterObject, RowHandler rowHandler) throws SQLException {
this.getLocalSqlMapSession().queryWithRowHandler(id, parameterObject, rowHandler);
}
@Override
public void queryWithRowHandler(String id, RowHandler rowHandler) throws SQLException {
this.getLocalSqlMapSession().queryWithRowHandler(id, rowHandler);
}
@Override
public PaginatedList queryForPaginatedList(String id, Object parameterObject, int pageSize) throws SQLException {
return this.getLocalSqlMapSession().queryForPaginatedList(id, parameterObject, pageSize);
}
@Override
public PaginatedList queryForPaginatedList(String id, int pageSize) throws SQLException {
return this.getLocalSqlMapSession().queryForPaginatedList(id, pageSize);
}
@Override
public Map queryForMap(String id, Object parameterObject, String keyProp) throws SQLException {
return this.getLocalSqlMapSession().queryForMap(id, parameterObject, keyProp);
}
@Override
public Map queryForMap(String id, Object parameterObject, String keyProp, String valueProp) throws SQLException {
return this.sqlMapClient.queryForMap(id, parameterObject, keyProp, valueProp);
}
@Override
public void startBatch() throws SQLException {
this.getLocalSqlMapSession().startBatch();
}
@Override
public int executeBatch() throws SQLException {
return this.getLocalSqlMapSession().executeBatch();
}
@Override
public List executeBatchDetailed() throws SQLException, BatchException {
return this.getLocalSqlMapSession().executeBatchDetailed();
}
@Override
public void startTransaction() throws SQLException {
this.getLocalSqlMapSession().startTransaction();
}
@Override
public void startTransaction(int transactionIsolation) throws SQLException {
this.getLocalSqlMapSession().startTransaction(transactionIsolation);
}
@Override
public void commitTransaction() throws SQLException {
this.getLocalSqlMapSession().commitTransaction();
}
@Override
public void endTransaction() throws SQLException {
try {
getLocalSqlMapSession().endTransaction();
} finally {
getLocalSqlMapSession().close();
}
}
@Override
public void setUserConnection(Connection connection) throws SQLException {
try {
getLocalSqlMapSession().setUserConnection(connection);
} finally {
if (connection == null) {
getLocalSqlMapSession().close();
}
}
}
@Override
public Connection getUserConnection() throws SQLException {
return this.getLocalSqlMapSession().getUserConnection();
}
@Override
public Connection getCurrentConnection() throws SQLException {
return this.getLocalSqlMapSession().getCurrentConnection();
}
@Override
public DataSource getDataSource() {
return this.getLocalSqlMapSession().getDataSource();
}
@Override
public <T> T getMapper(Class<T> type) {
return mapperRegistry.getMapper(type, this);
}
@Override
public SqlMapExecutorDelegate getDelegate() {
return this.delegate;
}
@Override
public void close() {
this.getLocalSqlMapSession().close();
}
private SqlMapSessionImpl getLocalSqlMapSession() {
SqlMapSessionImpl sqlMapSession = (SqlMapSessionImpl) localSqlMapSession.get();
if (sqlMapSession == null || sqlMapSession.isClosed()) {
sqlMapSession = (SqlMapSessionImpl) this.openSession();
localSqlMapSession.set(sqlMapSession);
}
return sqlMapSession;
}
}
这个类比较长,方法也比较多,但不难看懂。无非就是行为的适配转嫁。或者说是都委托给SqlMapSessionImpl来做真实的执行动作。
换句话说,我们需要在业务层中持有SqlSession的对象就可以调用getMapper方法获取到Mapper接口的代理对象。然后执行各种sql操作。这边先演示最后业务层的代码会张什么样。关于代理的详细执行过程,我们继续往下分析。
User user = new User();
user.setId("1");
user.setName("wujian");
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.insert(user);
} finally {
sqlSession.close();
}
这边下看下业务层最后的执行代码,会跟MyBaits一样。sqlSession可以通过Spring注入到业务代码中。后面会说到这部分。
接下来看看MapperMethod,MapperProxy,MapperProxyFactory,MapperRegistry
public class MapperRegistry {
private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
@SuppressWarnings("unchecked")
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
public <T> boolean hasMapper(Class<T> type) {
return knownMappers.containsKey(type);
}
public <T> void addMapper(Class<T> type) {
if (type.isInterface()) {
if (hasMapper(type)) {
throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
}
knownMappers.put(type, new MapperProxyFactory<T>(type));
}
}
public Collection<Class<?>> getMappers() {
return Collections.unmodifiableCollection(knownMappers.keySet());
}
public void addMappers(String packageName, Class<?> superType) {
ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
for (Class<?> mapperClass : mapperSet) {
addMapper(mapperClass);
}
}
public void addMappers(String packageName) {
addMappers(packageName, Object.class);
}
}
MapperRegistry 这个类与MyBatis3中的MapperRegistry是基本一样的。
public class MapperProxy<T> implements InvocationHandler, Serializable {
private static final long serialVersionUID = -6424540398559729838L;
private final SqlSession sqlSession;
private final Class<T> mapperInterface;
private final Map<Method, MapperMethod> methodCache;
public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
this.sqlSession = sqlSession;
this.mapperInterface = mapperInterface;
this.methodCache = methodCache;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
private MapperMethod cachedMapperMethod(Method method) {
MapperMethod mapperMethod = methodCache.get(method);
if (mapperMethod == null) {
mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getDelegate());
methodCache.put(method, mapperMethod);
}
return mapperMethod;
}
}
MapperProxy 这个类与MyBatis3中的MapperProxy是基本一样的。
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
public MapperProxyFactory(Class<T> mapperInterface) {
this.mapperInterface = mapperInterface;
}
public Class<T> getMapperInterface() {
return mapperInterface;
}
public Map<Method, MapperMethod> getMethodCache() {
return methodCache;
}
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
}
MapperProxyFactory 这个类与MyBatis3中的MapperProxyFactory是基本一样的。
public class MapperMethod {
private final SqlCommand command;
private final MethodSignature method;
public MapperMethod(Class<?> mapperInterface, Method method, SqlMapExecutorDelegate delegate) {
this.command = new SqlCommand(delegate, mapperInterface, method);
this.method = new MethodSignature(method);
}
public Object execute(SqlSession sqlSession, Object[] args) throws SQLException {
Object result = null;
if (StatementType.INSERT == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.insert(command.getName(), param);
} else if (StatementType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.update(command.getName(), param);
} else if (StatementType.DELETE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.delete(command.getName(), param);
} else if (StatementType.SELECT == command.getType()) {
if (method.returnsMany()) {
result = executeForMany(sqlSession, args);
} else if (method.returnsMap()) {
} else {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.queryForObject(command.getName(), param);
}
} else {
throw new BindingException("Unknown execution method for: " + command.getName());
}
if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type ("
+ method.getReturnType() + ").");
}
return result;
}
}
MapperMethod 这个类与MyBatis3中的MapperMethod有些不同。这边需要调用iBatis的一些适配处理,大家可以与MyBatis3中的做一些对比。
到此,适配器的部分已经基本完工。接下来要处理2个问题。
1.启动初始化
2.SqlSession要注入到业务层
我们新建一个类SqlSessionFactoryBean
public class SqlSessionFactoryBean implements FactoryBean<SqlSession>, InitializingBean, ApplicationListener<ApplicationEvent> {
private static final ThreadLocal<LobHandler> configTimeLobHandlerHolder = new ThreadLocal<LobHandler>();
public static LobHandler getConfigTimeLobHandler() {
return configTimeLobHandlerHolder.get();
}
private Resource[] configLocations;
private Resource[] mappingLocations;
private DataSource dataSource;
private SqlMapClient sqlMapClient;
private SqlSession sqlSession;
private String packageName;
private MapperRegistry mapperRegistry = new MapperRegistry();
public SqlSessionFactoryBean() {
this.transactionConfigProperties = new Properties();
this.transactionConfigProperties.setProperty("SetAutoCommitAllowed", "false");
}
@Override
public SqlSession getObject() {
return this.sqlSession;
}
@Override
public void afterPropertiesSet() throws Exception {
if (this.lobHandler != null) {
configTimeLobHandlerHolder.set(this.lobHandler);
}
try {
this.sqlMapClient = buildSqlMapClient(this.configLocations, this.mappingLocations, this.sqlMapClientProperties);
// Tell the SqlMapClient to use the given DataSource, if any.
if (this.dataSource != null) {
TransactionConfig transactionConfig = (TransactionConfig) this.transactionConfigClass.newInstance();
DataSource dataSourceToUse = this.dataSource;
if (this.useTransactionAwareDataSource && !(this.dataSource instanceof TransactionAwareDataSourceProxy)) {
dataSourceToUse = new TransactionAwareDataSourceProxy(this.dataSource);
}
transactionConfig.setDataSource(dataSourceToUse);
transactionConfig.initialize(this.transactionConfigProperties);
applyTransactionConfig(this.sqlMapClient, transactionConfig);
}
// 适配器
this.sqlSession = new SqlSessionDefault(this.sqlMapClient, this.mapperRegistry);
this.mapperRegistry.addMappers(packageName);
} finally {
if (this.lobHandler != null) {
configTimeLobHandlerHolder.remove();
}
}
}
protected SqlMapClient buildSqlMapClient(Resource[] configLocations, Resource[] mappingLocations, Properties properties) throws IOException {
if (ObjectUtils.isEmpty(configLocations)) {
throw new IllegalArgumentException("At least 1 'configLocation' entry is required");
}
SqlMapClient client = null;
SqlMapConfigParser configParser = new SqlMapConfigParser();
for (Resource configLocation : configLocations) {
InputStream is = configLocation.getInputStream();
try {
client = configParser.parse(is, properties);
} catch (RuntimeException ex) {
throw new NestedIOException("Failed to parse config resource: " + configLocation, ex.getCause());
}
}
if (mappingLocations != null) {
SqlMapParser mapParser = SqlMapParserFactory.createSqlMapParser(configParser);
for (Resource mappingLocation : mappingLocations) {
try {
mapParser.parse(mappingLocation.getInputStream());
} catch (NodeletException ex) {
throw new NestedIOException("Failed to parse mapping resource: " + mappingLocation, ex);
}
}
}
return client;
}
}
SqlSessionFactoryBean是spring的一个factoryBean,在初始化时,会被加载。请关注其中2行代码。分别是sqlSession的创建和mapper的加载。
// 适配器
this.sqlSession = new SqlSessionDefault(this.sqlMapClient, this.mapperRegistry);
this.mapperRegistry.addMappers(packageName);
这样。sqlSession就可以在应用中被随意注入了。
总结
到此,我们就把iBatis-mapper适配器的整个过程都已经说完了。有兴趣的小伙伴可以自动动手操作下。经过大量的测试是可以在实际生产中使用的。
抱歉,这边由于篇幅问题,没有贴出整个适配层的所有细节代码。包括Exception的处理,MyBatis3中特别好用的的注解@Param的实现方式。对此有兴趣或者想深入了解的小伙伴可以给我留言或者找我源代码。这边贴下我工程中的类。

本篇中,我们只讲了适配过程。还没有说iBatis-generator的实现。下篇文章中会详细讲解。