前言
mybatis作为一个流行了多年的orm框架,广泛地被各大互联网公司所使用,它的特点是半自动sql,需要自己手写sql,非常灵活,简单小巧。
mybatis启动源码
首先先写一个mybatis的配置文件(当然现在已经被springboot自动配置类所取代),大家应该很熟悉了:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--properties 扫描属性文件.properties -->
<properties resource="db.properties"></properties>
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<!-- <plugins>
<plugin interceptor="com.test.plugins.ExamplePlugin" ></plugin>
</plugins>-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<!--// mybatis内置了JNDI、POOLED、UNPOOLED三种类型的数据源,其中POOLED对应的实现为org.apache.ibatis.datasource.pooled.PooledDataSource,它是mybatis自带实现的一个同步、线程安全的数据库连接池 一般在生产中,我们会使用c3p0或者druid连接池-->
<dataSource type="POOLED">
<property name="driver" value="${mysql.driverClass}"/>
<property name="url" value="${mysql.jdbcUrl}"/>
<property name="username" value="${mysql.user}"/>
<property name="password" value="${mysql.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.test.mapper"/>
</mappers>
</configuration>
再写一个测试的main方法:
public static void main(String[] args) {
String resource = "mybatis-config.xml";
Reader reader;
try {
//将XML配置文件构建为Configuration配置类
reader = Resources.getResourceAsReader(resource);
// 通过加载配置文件流构建一个SqlSessionFactory DefaultSqlSessionFactory
//在springboot中会通过配置文件和自动配置类构建全局Configuration
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
//通过DefaultSqlSessionFactory拿到SqlSession
SqlSession session = sqlSessionFactory.openSession();
try {
// 执行查询 底层执行jdbc
//User user = (User)session.selectOne("com.paradox.mapper.UserMapper.selectById", 1);
//获取mapper对象,就是我们写的mapper接口,是一个代理对象
UserMapper mapper = session.getMapper(UserMapper.class);
System.out.println(mapper.getClass());
//执行sql
User user = mapper.selectById(1L);
session.commit();
System.out.println(user.getUserName());
} catch (Exception e) {
e.printStackTrace();
}finally {
session.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
附上mapper文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.paradox.mapper.UserMapper">
<cache ></cache>
<resultMap id="result" type="com.paradox.entity.User" >
<id column="id" jdbcType="INT" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="create_time" jdbcType="DATE" property="createTime" />
</resultMap>
<select id="selectById" resultMap="result">
select id,user_name,create_time from t_user where id=#{param1}
</select>
</mapper>
完成,可以看到mybatis的使用非常简单,下面直接进入源码,首先是创建SqlSessionFactory:
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
public SqlSessionFactory build(Reader reader) {
return build(reader, null, null);
}
public SqlSessionFactory build(Reader reader, String environment, Properties properties) {
try {
XMLConfigBuilder parser = new XMLConfigBuilder(reader, environment, properties);
//parser.parse()解析配置文件,把配置文件解析为一个全局的Configuration对象
return build(parser.parse());
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error building SqlSession.", e);
} finally {
ErrorContext.instance().reset();
try {
reader.close();
} catch (IOException e) {
// Intentionally ignore. Prefer previous error.
}
}
}
public SqlSessionFactory build(Configuration config) {
//用全局配置对象创建DefaultSqlSessionFactory
return new DefaultSqlSessionFactory(config);
}
configuration这个对象在mybatis种非常重要,是全局的配置类, parser.parse()这个方法会解析配置文件包括我们写的mapper文件,解析成一个configuration对象,其中mapper中的每一个标签如<select></select>会被解析成一个个MapperStatment对象放入configuration,关于标签的解析并不简单,涉及静态以及动态sql的解析,暂不分析。
//通过DefaultSqlSessionFactory拿到SqlSession SqlSession session = sqlSessionFactory.openSession();
public SqlSession openSession() {
return openSessionFromDataSource(configuration.getDefaultExecutorType(), null, false);
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
try {
//全局配置中的Environment,数据源就在里面
final Environment environment = configuration.getEnvironment();
//从Environment拿到TransactionFactory事务工厂
final TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
//用事务工厂创建一个tx,事务
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
//获取sql执行器
final Executor executor = configuration.newExecutor(tx, execType);
//用全局配置对象,sql执行器创建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();
}
}
看一下获取sql执行器的逻辑:
public Executor newExecutor(Transaction transaction, ExecutorType executorType) {
executorType = executorType == null ? defaultExecutorType : executorType;
executorType = executorType == null ? ExecutorType.SIMPLE : executorType;
//executorTyp为ExecutorType.SIMPLE
Executor executor;
if (ExecutorType.BATCH == executorType) {
executor = new BatchExecutor(this, transaction);
} else if (ExecutorType.REUSE == executorType) {
executor = new ReuseExecutor(this, transaction);
} else {
//创建SimpleExecutor,简单的sql执行器
executor = new SimpleExecutor(this, transaction);
}
if (cacheEnabled) {
//cacheEnabled一般默认为true,包装为具有缓存功能的执行器
executor = new CachingExecutor(executor);
}
//加入拦截器,就是调用所有目标为Executor的拦截器的plugin方法,用动态代理实现
executor = (Executor) interceptorChain.pluginAll(executor);
return executor;
}
看一下Excutor的几个主要的属性:
this.transaction = transaction;//事务对象
this.deferredLoads = new ConcurrentLinkedQueue<>();
this.localCache = new PerpetualCache("LocalCache");//一级缓存
this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
this.closed = false;
this.configuration = configuration;//全局配置对象
this.wrapper = this;
注意:CachingExecutor主要实现了mybatis的二级缓存功能,不过现在已经不太常用了:
private final TransactionalCacheManager tcm = new TransactionalCacheManager();//二级缓存
接下来是用SqlSession获取mapper对象,就是我们写的mapper接口,是一个代理对象:
public <T> T getMapper(Class<T> type) {
//用configuration获取
return configuration.getMapper(type, this);
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//从mapperRegistry获取mapper的代理对象,mapperRegistry为mapper注册中心,在
//构建全局配置的时候,所有的mapper文件及对应接口被解析,并创建相应的代理工厂注册到mapperRegistry
return mapperRegistry.getMapper(type, sqlSession);
}
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
//通过mapper接口的类型获取代理工厂
final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
}
try {
//为mapper创建动态代理
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception e) {
throw new BindingException("Error getting mapper instance. Cause: " + e, e);
}
}
public T newInstance(SqlSession sqlSession) {
//创建MapperProxy,MapperProxy实现了InvocationHandler
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
return newInstance(mapperProxy);
}
protected T newInstance(MapperProxy<T> mapperProxy) {
//真正创建代理对象 jdk动态代理
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
当我们执行接口的相应方法时,会来到InvocationHandler的invoke方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
//object的方法
return method.invoke(this, args);
} else {
//获取MapperMethodInvoker并执行方法
return cachedInvoker(method).invoke(proxy, method, args, sqlSession);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
private MapperMethodInvoker cachedInvoker(Method method) throws Throwable {
try {
//map的computeIfAbsent方法,获取对应与method的MapperMethodInvoker,先从缓存methodCache中取
//缓存没有则创建
return MapUtil.computeIfAbsent(methodCache, method, m -> {
if (m.isDefault()) {
//如果是接口的默认方法,略过
try {
if (privateLookupInMethod == null) {
return new DefaultMethodInvoker(getMethodHandleJava8(method));
} else {
return new DefaultMethodInvoker(getMethodHandleJava9(method));
}
} catch (IllegalAccessException | InstantiationException | InvocationTargetException
| NoSuchMethodException e) {
throw new RuntimeException(e);
}
} else {
//不是默认方法,创建MethodInvoker
return new PlainMethodInvoker(new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
}
});
} catch (RuntimeException re) {
Throwable cause = re.getCause();
throw cause == null ? re : cause;
}
}
public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
//创建SqlCommand,sql标签名称,sql类型等
this.command = new SqlCommand(config, mapperInterface, method);
//创建方法签名,保存了方法的返回信息
this.method = new MethodSignature(config, mapperInterface, method);
}
用MethodInvoker执行方法:
public Object invoke(Object proxy, Method method, Object[] args, SqlSession sqlSession) throws Throwable {
return mapperMethod.execute(sqlSession, args);
}
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
switch (command.getType()) {
//...
//以查询操作中查询一条记录为例
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);
//执行查询语句,使用DefaultSqlSession,如果是和spring整合的话会使用SqlSessionTemplate
result = sqlSession.selectOne(command.getName(), param);
if (method.returnsOptional()
&& (result == null || !method.getReturnType().equals(result.getClass()))) {
result = Optional.ofNullable(result);
}
}
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;
}
sqlsession执行查询:
public <T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
//selectOne调用也是调用selectList方法,取第一个就行
List<T> list = this.selectList(statement, parameter);
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) {
//查出大于一个的话抛异常
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
public <E> List<E> selectList(String statement, Object parameter) {
//statement唯一指定了是哪个sql标签,namespace+sql标签id
//RowBounds.DEFAULT表示分页数据,0到Integer.MAX_VALUE,mybatis默认使用的是逻辑分页
//也就是使用内存分页
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
private <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
//从全局配置获取MappedStatement,一个MappedStatement对应一个sql标签节点
MappedStatement ms = configuration.getMappedStatement(statement);
//用executor执行器执行sql,首先会包装参数wrapCollection(parameter)
//主要会处理集合参数对象,转换成map,如果就是java对象则不会处理
return executor.query(ms, wrapCollection(parameter), rowBounds, handler);
} catch (Exception e) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + e, e);
} finally {
ErrorContext.instance().reset();
}
}
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler) throws SQLException {
//获取boundSql,可以理解为sql语句,还包括参数信息
BoundSql boundSql = ms.getBoundSql(parameter);
//一级缓存的key
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
//从一级缓存中获取,默认以及缓存都时开启的,一级缓存时session级别的
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
//缓存没有,则从数据库查
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
一级缓存没有,则正式查询:
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);//将一个占位对象放入一级缓存
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);//加入一级缓存
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
public <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
//创建StatementHandler,一般为PreparedStatementHandler,
//在创建StatementHandler中还会创建parameterHandler和resultSetHandler
//parameterHandler用来组装参数,resultSetHandler用来处理结果集
StatementHandler handler = configuration.newStatementHandler(wrapper, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.query(stmt, resultHandler);
} finally {
closeStatement(stmt);
}
}
public <E> List<E> query(Statement statement, ResultHandler resultHandler) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
//用jdk的PreparedStatement执行sql
ps.execute();
//对结果集进行处理
return resultSetHandler.handleResultSets(ps);
}
总结
至此一条sql查询语句执行完了,可以看到mybatis的源码还是比较易读的,一条路走到底,思路比较清晰,期间忽略了二级缓存的分析,现在一般都不用了。至于mapper文件的解析以及mybatis插件的原理,后面有机会讲解。