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中用到的设计模式还有不少,但愿本文能起到一个引导的做用,让你们多看源码,关注设计模式,共同窗习,共同进步。
章茂瑜,民生科技有限公司,用户体验技术部,移动金融开发平台开发工程师。