Mybatis的啓動方式有兩種,交給Spring來啓動和編碼方式啓動。第一種方式:若是項目中用到了mybatis-spring.jar,那大可能是經過Spring來啓動。咱們重點介紹一下第二種方式:編碼啓動,獲取sqlsession的依賴關係圖以下:mysql
Reader reader = Resources.getResourceAsReader("Mybatis配置文件路徑");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();複製代碼
其中SqlSession和SqlSessionFactory這兩個接口,及DefaultSqlSession和DefaultSqlSessionFactory這兩個默認實現類,就是典型的工廠方法模式的實現。一個基礎接口(SqlSession)定義了功能,每一個實現接口的子類(DefaultSqlSession)就是產品,而後定義一個工廠接口(SqlSessionFactory),實現了工廠接口的就是工廠(DefaultSqlSessionFactory),採用工廠方法模式的優勢是:一旦須要增長新的sqlsession實現類,直接增長新的SqlSessionFactory的實現類,不須要修改以前的代碼,更好的知足了開閉原則。spring
在SqlSessionFactoryBuilder中構建SqlSessionFactory分爲了兩步:sql
public SqlSessionFactory build(InputStream inputStream,String environment,Properties properties) {
...
XMLConfigBuilder parser = new XMLConfigBuilder(inputStream, environment, properties);
return build(parser.parse());
...
}
public SqlSessionFactory build(Configuration config) {
return new DefaultSqlSessionFactory(config);
}複製代碼
建立datasource對象也有兩種方式,交給Spring來建立和讀取mybatis配置文件建立。數據庫
Jndi: 使用jndi實現的數據源, 經過JNDI上下文中取值apache
Pooled:使用鏈接池的數據源設計模式
Unpooled:不使用鏈接池的數據源數組
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
複製代碼
Executor是MyBatis執行器,負責SQL語句的生成和查詢緩存的維護。Executor的功能和做用是:緩存
@Override
public int update(MappedStatement ms, Object parameter) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
clearLocalCache();
return doUpdate(ms, parameter);
}複製代碼
這樣實現的優勢是:一、封裝不變部分,擴展可變部分。二、提取公共代碼,便於維護。三、行爲由父類控制,子類實現。bash
MyBatis 容許在sql語句執行過程當中的某一點進行攔截調用,具體實現是經過對Executor、StatementHandler、PameterHandler和ResultSetHandler進行攔截代理。其中的業務含義以下介紹:session
經過查看Configuration類的源代碼咱們能夠看到,每次都對目標對象進行代理鏈的生成。
public ParameterHandler newParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
ParameterHandler parameterHandler = mappedStatement.getLang().createParameterHandler(mappedStatement, parameterObject, boundSql);
parameterHandler = (ParameterHandler) interceptorChain.pluginAll(parameterHandler);
return parameterHandler;
}
public ResultSetHandler newResultSetHandler(Executor executor, MappedStatement mappedStatement, RowBounds rowBounds, ParameterHandler parameterHandler,
ResultHandler resultHandler, BoundSql boundSql) {
ResultSetHandler resultSetHandler = new DefaultResultSetHandler(executor, mappedStatement, parameterHandler, resultHandler, boundSql, rowBounds);
resultSetHandler = (ResultSetHandler) interceptorChain.pluginAll(resultSetHandler);
return resultSetHandler;
}
public StatementHandler newStatementHandler(Executor executor, MappedStatement mappedStatement, Object parameterObject, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
StatementHandler statementHandler = new RoutingStatementHandler(executor, mappedStatement, parameterObject, rowBounds, resultHandler, boundSql);
statementHandler = (StatementHandler) interceptorChain.pluginAll(statementHandler);
return statementHandler;
}
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
executor = new CachingExecutor(executor);
}
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}複製代碼
以常見的PageInterceptor(給查詢語句增長分頁)爲例(mybatis 攔截器只能使用註解實現):
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class,RowBounds.class, ResultHandler.class})
})
@Slf4j
public class PageInterceptor implements Interceptor {
...
/**
* 執行攔截邏輯的方法
*/
@Override
public Object intercept(Invocation invocation) throws Throwable {
...
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
...
}
複製代碼
Plugin類的源碼以下:
/**
* 繼承了InvocationHandler
*/public class Plugin implements InvocationHandler {
//目標對象
private final Object target;
// 攔截器
private final Interceptor interceptor;
private final Map<Class<?>, Set<Method>> signatureMap;
private Plugin(Object target, Interceptor interceptor, Map<Class<?>, Set<Method>> signatureMap) {
this.target = target;
this.interceptor = interceptor;
this.signatureMap = signatureMap;
}
//對一個目標對象進行包裝,生成代理類。
public static Object wrap(Object target, Interceptor interceptor) {
//首先根據interceptor上面定義的註解 獲取須要攔截的信息
Map<Class<?>, Set<Method>> signatureMap = getSignatureMap(interceptor);
//目標對象的Class
Class<?> type = target.getClass();
//返回須要攔截的接口信息
Class<?>[] interfaces = getAllInterfaces(type, signatureMap);
//若是長度爲>0 則返回代理類 不然不作處理
if (interfaces.length > 0) {
return Proxy.newProxyInstance(
type.getClassLoader(),
interfaces,
new Plugin(target, interceptor, signatureMap));
}
return target;
}
//代理對象每次調用的方法
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
//經過method參數定義的類 去signatureMap當中查詢須要攔截的方法集合
Set<Method> methods = signatureMap.get(method.getDeclaringClass());
//判斷是否須要攔截
if (methods != null && methods.contains(method)) {
//執行攔截器的攔截方法
return interceptor.intercept(new Invocation(target, method, args));
}
//不攔截 直接經過目標對象調用方法
return method.invoke(target, args);
} catch (Exception e) {
throw ExceptionUtil.unwrapThrowable(e);
}
}
//根據攔截器接口(Interceptor)實現類上面的註解獲取相關信息
private static Map<Class<?>, Set<Method>> getSignatureMap(Interceptor interceptor) {
//獲取註解信息@Intercepts
Intercepts interceptsAnnotation = interceptor.getClass().getAnnotation(Intercepts.class);
if (interceptsAnnotation == null) {//爲空則拋出異常
throw new PluginException("No @Intercepts annotation was found in interceptor " + interceptor.getClass().getName());
}
//得到Signature註解信息 是一個數組
Signature[] sigs = interceptsAnnotation.value();
Map<Class<?>, Set<Method>> signatureMap = new HashMap<Class<?>, Set<Method>>();
//循環註解信息
for (Signature sig : sigs) {
//根據Signature註解定義的type信息去signatureMap當中查詢須要攔截方法的集合
Set<Method> methods = signatureMap.get(sig.type());
if (methods == null) { //第一次確定爲null 就建立一個並放入signatureMap
methods = new HashSet<Method>();
signatureMap.put(sig.type(), methods);
}
try {
//找到sig.type當中定義的方法 並加入到集合
Method method = sig.type().getMethod(sig.method(), sig.args());
methods.add(method);
} catch (NoSuchMethodException e) {
throw new PluginException("Could not find method > } } return signatureMap; } //根據對象類型與signatureMap獲取接口信息 private static Class<?>[] getAllInterfaces(Class<?> type, Map<Class<?>, Set<Method>> signatureMap) { Set<Class<?>> interfaces = new HashSet<Class<?>>(); //循環type類型的接口信息 若是該類型存在與signatureMap當中則加入到set當中去 while (type != null) { for (Class<?> c : type.getInterfaces()) { if (signatureMap.containsKey(c)) { interfaces.add(c); } } type = type.getSuperclass(); } //轉換爲數組返回 return interfaces.toArray(new Class<?>[interfaces.size()]); } } 複製代碼
代理模式的設計意圖是爲一個對象提供一個替身或者佔位符以控制對這個對象的訪問,它給目標對象提供一個代理對象,由代理對象控制對目標對象的訪問。
JAVA動態代理與靜態代理相對,靜態代理是在編譯期就已經肯定代理類和真實類的關係,而且生成代理類的。而動態代理是在運行期利用JVM的反射機制生成代理類,這裏是直接生成類的字節碼,而後經過類加載器載入JAVA虛擬機執行。JDK動態代理的實現是在運行時,根據一組接口定義,使用Proxy、InvocationHandler等工具類去生成一個代理類和代理類實例。
Mybatis中用到的設計模式還有不少,但願本文能起到一個引導的做用,讓你們多看源碼,關注設計模式,共同窗習,共同進步。
章茂瑜,民生科技有限公司,用戶體驗技術部,移動金融開發平臺開發工程師。