1. XMLConfigBuilder 用于XML解析即解析Mybatis的配置文件和映射文件;生成Configuration文件
只解析一次,因此启动后的编写xml需要重启
涉及其他类:
1.1 XPathParser:真实解析xml的是他
1.2 Configuration:特别重要的类,所有的配置信息都存在这
2. SqlSessionFactoryBuilder
这个类是用于创建SqlSessionFactory的,本质上是通过I0读取xml,然后交给XMLConfigBuilder去解析到底Configuration;然后根据Configuration创建DefaultSqlSessionFactory
3. SqlSessionFactory:此类没有啥好说的,主要获取SqlSesson对象(涉及到数据源、事务)
public class DefaultSqlSessionFactory implements SqlSessionFactory {
private final Configuration configuration;
public DefaultSqlSessionFactory(Configuration configuration) {
this.configuration = configuration;
}
public SqlSession openSession() {
return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, false);
}
public SqlSession openSession(boolean autoCommit) {
return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, autoCommit);
}
public SqlSession openSession(ExecutorType execType) {
return this.openSessionFromDataSource(execType, (TransactionIsolationLevel)null, false);
}
public SqlSession openSession(TransactionIsolationLevel level) {
return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), level, false);
}
public SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level) {
return this.openSessionFromDataSource(execType, level, false);
}
public SqlSession openSession(ExecutorType execType, boolean autoCommit) {
return this.openSessionFromDataSource(execType, (TransactionIsolationLevel)null, autoCommit);
}
public SqlSession openSession(Connection connection) {
return this.openSessionFromConnection(this.configuration.getDefaultExecutorType(), connection);
}
public SqlSession openSession(ExecutorType execType, Connection connection) {
return this.openSessionFromConnection(execType, connection);
}
public Configuration getConfiguration() {
return this.configuration;
}
private SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit) {
Transaction tx = null;
DefaultSqlSession var8;
try {
Environment environment = this.configuration.getEnvironment();
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
Executor executor = this.configuration.newExecutor(tx, execType);
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
} catch (Exception var12) {
this.closeTransaction(tx);
throw ExceptionFactory.wrapException("Error opening session. Cause: " + var12, var12);
} finally {
ErrorContext.instance().reset();
}
return var8;
}
private SqlSession openSessionFromConnection(ExecutorType execType, Connection connection) {
DefaultSqlSession var8;
try {
boolean autoCommit;
try {
autoCommit = connection.getAutoCommit();
} catch (SQLException var13) {
autoCommit = true;
}
Environment environment = this.configuration.getEnvironment();
TransactionFactory transactionFactory = this.getTransactionFactoryFromEnvironment(environment);
Transaction tx = transactionFactory.newTransaction(connection);
Executor executor = this.configuration.newExecutor(tx, execType);
var8 = new DefaultSqlSession(this.configuration, executor, autoCommit);
} catch (Exception var14) {
throw ExceptionFactory.wrapException("Error opening session. Cause: " + var14, var14);
} finally {
ErrorContext.instance().reset();
}
return var8;
}
private TransactionFactory getTransactionFactoryFromEnvironment(Environment environment) {
return (TransactionFactory)(environment != null && environment.getTransactionFactory() != null ? environment.getTransactionFactory() : new ManagedTransactionFactory());
}
private void closeTransaction(Transaction tx) {
if (tx != null) {
try {
tx.close();
} catch (SQLException var3) {
;
}
}
}
}
4. DefaultSqlSession :我们所说SqlSession一般就是指的这个类
这个回头再深入讲解一下
public class DefaultSqlSession implements SqlSession {
private Configuration configuration;
private Executor executor;
private boolean autoCommit;
private boolean dirty;
private List<Cursor<?>> cursorList;
public DefaultSqlSession(Configuration configuration, Executor executor, boolean autoCommit) {
this.configuration = configuration;
this.executor = executor;
this.dirty = false;
this.autoCommit = autoCommit;
}
public DefaultSqlSession(Configuration configuration, Executor executor) {
this(configuration, executor, false);
}
public <T> T selectOne(String statement) {
return this.selectOne(statement, (Object)null);
}
public <T> T selectOne(String statement, Object parameter) { //可以看出selectOne本质走的是selectList;
List<T> list = this.selectList(statement, parameter);
if (list.size() == 1) {
return list.get(0);
} else if (list.size() > 1) { //这也是很多兄弟问我的为啥报错,因为数据库有多条啊,最好在selectOne加上SELECT * FROM `sys_dept` LIMIT 1;
throw new TooManyResultsException("Expected one result (or null) to be returned by selectOne(), but found: " + list.size());
} else {
return null;
}
}
public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
return this.selectMap(statement, (Object)null, mapKey, RowBounds.DEFAULT);
}
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
return this.selectMap(statement, parameter, mapKey, RowBounds.DEFAULT);
}
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
List<? extends V> list = this.selectList(statement, parameter, rowBounds);
DefaultMapResultHandler<K, V> mapResultHandler = new DefaultMapResultHandler(mapKey, this.configuration.getObjectFactory(), this.configuration.getObjectWrapperFactory(), this.configuration.getReflectorFactory());
DefaultResultContext<V> context = new DefaultResultContext();
Iterator var8 = list.iterator();
while(var8.hasNext()) {
V o = var8.next();
context.nextResultObject(o);
mapResultHandler.handleResult(context);
}
return mapResultHandler.getMappedResults();
}
public <T> Cursor<T> selectCursor(String statement) {
return this.selectCursor(statement, (Object)null);
}
public <T> Cursor<T> selectCursor(String statement, Object parameter) {
return this.selectCursor(statement, parameter, RowBounds.DEFAULT);
}
public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) {
Cursor var6;
try {
MappedStatement ms = this.configuration.getMappedStatement(statement);
Cursor<T> cursor = this.executor.queryCursor(ms, this.wrapCollection(parameter), rowBounds);
this.registerCursor(cursor);
var6 = cursor;
} catch (Exception var10) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + var10, var10);
} finally {
ErrorContext.instance().reset();
}
return var6;
}
public <E> List<E> selectList(String statement) {
return this.selectList(statement, (Object)null);
}
public <E> List<E> selectList(String statement, Object parameter) {
return this.selectList(statement, parameter, RowBounds.DEFAULT);
}
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
List var5;
try {
MappedStatement ms = this.configuration.getMappedStatement(statement);
var5 = this.executor.query(ms, this.wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
} catch (Exception var9) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + var9, var9);
} finally {
ErrorContext.instance().reset();
}
return var5;
}
public void select(String statement, Object parameter, ResultHandler handler) {
this.select(statement, parameter, RowBounds.DEFAULT, handler);
}
public void select(String statement, ResultHandler handler) {
this.select(statement, (Object)null, RowBounds.DEFAULT, handler);
}
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
try {
MappedStatement ms = this.configuration.getMappedStatement(statement);
this.executor.query(ms, this.wrapCollection(parameter), rowBounds, handler);
} catch (Exception var9) {
throw ExceptionFactory.wrapException("Error querying database. Cause: " + var9, var9);
} finally {
ErrorContext.instance().reset();
}
}
public int insert(String statement) {
return this.insert(statement, (Object)null);
}
public int insert(String statement, Object parameter) {
return this.update(statement, parameter);
}
public int update(String statement) {
return this.update(statement, (Object)null);
}
public int update(String statement, Object parameter) {
int var4;
try {
this.dirty = true;
MappedStatement ms = this.configuration.getMappedStatement(statement);
var4 = this.executor.update(ms, this.wrapCollection(parameter));
} catch (Exception var8) {
throw ExceptionFactory.wrapException("Error updating database. Cause: " + var8, var8);
} finally {
ErrorContext.instance().reset();
}
return var4;
}
public int delete(String statement) {
return this.update(statement, (Object)null);
}
public int delete(String statement, Object parameter) {
return this.update(statement, parameter);
}
public void commit() {
this.commit(false);
}
public void commit(boolean force) {
try {
this.executor.commit(this.isCommitOrRollbackRequired(force));
this.dirty = false;
} catch (Exception var6) {
throw ExceptionFactory.wrapException("Error committing transaction. Cause: " + var6, var6);
} finally {
ErrorContext.instance().reset();
}
}
public void rollback() {
this.rollback(false);
}
public void rollback(boolean force) {
try {
this.executor.rollback(this.isCommitOrRollbackRequired(force));
this.dirty = false;
} catch (Exception var6) {
throw ExceptionFactory.wrapException("Error rolling back transaction. Cause: " + var6, var6);
} finally {
ErrorContext.instance().reset();
}
}
public List<BatchResult> flushStatements() {
List var1;
try {
var1 = this.executor.flushStatements();
} catch (Exception var5) {
throw ExceptionFactory.wrapException("Error flushing statements. Cause: " + var5, var5);
} finally {
ErrorContext.instance().reset();
}
return var1;
}
public void close() {
try {
this.executor.close(this.isCommitOrRollbackRequired(false));
this.closeCursors();
this.dirty = false;
} finally {
ErrorContext.instance().reset();
}
}
private void closeCursors() {
if (this.cursorList != null && this.cursorList.size() != 0) {
Iterator var1 = this.cursorList.iterator();
while(var1.hasNext()) {
Cursor cursor = (Cursor)var1.next();
try {
cursor.close();
} catch (IOException var4) {
throw ExceptionFactory.wrapException("Error closing cursor. Cause: " + var4, var4);
}
}
this.cursorList.clear();
}
}
public Configuration getConfiguration() {
return this.configuration;
}
public <T> T getMapper(Class<T> type) {
return this.configuration.getMapper(type, this);
}
public Connection getConnection() {
try {
return this.executor.getTransaction().getConnection();
} catch (SQLException var2) {
throw ExceptionFactory.wrapException("Error getting a new connection. Cause: " + var2, var2);
}
}
public void clearCache() {
this.executor.clearLocalCache();
}
private <T> void registerCursor(Cursor<T> cursor) {
if (this.cursorList == null) {
this.cursorList = new ArrayList();
}
this.cursorList.add(cursor);
}
private boolean isCommitOrRollbackRequired(boolean force) {
return !this.autoCommit && this.dirty || force;
}
private Object wrapCollection(Object object) {
DefaultSqlSession.StrictMap map;
if (object instanceof Collection) {
map = new DefaultSqlSession.StrictMap();
map.put("collection", object);
if (object instanceof List) {
map.put("list", object);
}
return map;
} else if (object != null && object.getClass().isArray()) {
map = new DefaultSqlSession.StrictMap();
map.put("array", object);
return map;
} else {
return object;
}
}
public static class StrictMap<V> extends HashMap<String, V> {
private static final long serialVersionUID = -5741767162221585340L;
public StrictMap() {
}
public V get(Object key) {
if (!super.containsKey(key)) {
throw new BindingException("Parameter '" + key + "' not found. Available parameters are " + this.keySet());
} else {
return super.get(key);
}
}
}
}
5. SqlSessionManager:这个类回头聊//TODO
public class SqlSessionManager implements SqlSessionFactory, SqlSession {
private final SqlSessionFactory sqlSessionFactory;
private final SqlSession sqlSessionProxy;
private ThreadLocal<SqlSession> localSqlSession = new ThreadLocal();
private SqlSessionManager(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
this.sqlSessionProxy = (SqlSession)Proxy.newProxyInstance(SqlSessionFactory.class.getClassLoader(), new Class[]{SqlSession.class}, new SqlSessionManager.SqlSessionInterceptor());
}
public static SqlSessionManager newInstance(Reader reader) {
return new SqlSessionManager((new SqlSessionFactoryBuilder()).build(reader, (String)null, (Properties)null));
}
public static SqlSessionManager newInstance(Reader reader, String environment) {
return new SqlSessionManager((new SqlSessionFactoryBuilder()).build(reader, environment, (Properties)null));
}
public static SqlSessionManager newInstance(Reader reader, Properties properties) {
return new SqlSessionManager((new SqlSessionFactoryBuilder()).build(reader, (String)null, properties));
}
public static SqlSessionManager newInstance(InputStream inputStream) {
return new SqlSessionManager((new SqlSessionFactoryBuilder()).build(inputStream, (String)null, (Properties)null));
}
public static SqlSessionManager newInstance(InputStream inputStream, String environment) {
return new SqlSessionManager((new SqlSessionFactoryBuilder()).build(inputStream, environment, (Properties)null));
}
public static SqlSessionManager newInstance(InputStream inputStream, Properties properties) {
return new SqlSessionManager((new SqlSessionFactoryBuilder()).build(inputStream, (String)null, properties));
}
public static SqlSessionManager newInstance(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionManager(sqlSessionFactory);
}
public void startManagedSession() {
this.localSqlSession.set(this.openSession());
}
public void startManagedSession(boolean autoCommit) {
this.localSqlSession.set(this.openSession(autoCommit));
}
public void startManagedSession(Connection connection) {
this.localSqlSession.set(this.openSession(connection));
}
public void startManagedSession(TransactionIsolationLevel level) {
this.localSqlSession.set(this.openSession(level));
}
public void startManagedSession(ExecutorType execType) {
this.localSqlSession.set(this.openSession(execType));
}
public void startManagedSession(ExecutorType execType, boolean autoCommit) {
this.localSqlSession.set(this.openSession(execType, autoCommit));
}
public void startManagedSession(ExecutorType execType, TransactionIsolationLevel level) {
this.localSqlSession.set(this.openSession(execType, level));
}
public void startManagedSession(ExecutorType execType, Connection connection) {
this.localSqlSession.set(this.openSession(execType, connection));
}
public boolean isManagedSessionStarted() {
return this.localSqlSession.get() != null;
}
public SqlSession openSession() {
return this.sqlSessionFactory.openSession();
}
public SqlSession openSession(boolean autoCommit) {
return this.sqlSessionFactory.openSession(autoCommit);
}
public SqlSession openSession(Connection connection) {
return this.sqlSessionFactory.openSession(connection);
}
public SqlSession openSession(TransactionIsolationLevel level) {
return this.sqlSessionFactory.openSession(level);
}
public SqlSession openSession(ExecutorType execType) {
return this.sqlSessionFactory.openSession(execType);
}
public SqlSession openSession(ExecutorType execType, boolean autoCommit) {
return this.sqlSessionFactory.openSession(execType, autoCommit);
}
public SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level) {
return this.sqlSessionFactory.openSession(execType, level);
}
public SqlSession openSession(ExecutorType execType, Connection connection) {
return this.sqlSessionFactory.openSession(execType, connection);
}
public Configuration getConfiguration() {
return this.sqlSessionFactory.getConfiguration();
}
public <T> T selectOne(String statement) {
return this.sqlSessionProxy.selectOne(statement);
}
public <T> T selectOne(String statement, Object parameter) {
return this.sqlSessionProxy.selectOne(statement, parameter);
}
public <K, V> Map<K, V> selectMap(String statement, String mapKey) {
return this.sqlSessionProxy.selectMap(statement, mapKey);
}
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey) {
return this.sqlSessionProxy.selectMap(statement, parameter, mapKey);
}
public <K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey, RowBounds rowBounds) {
return this.sqlSessionProxy.selectMap(statement, parameter, mapKey, rowBounds);
}
public <T> Cursor<T> selectCursor(String statement) {
return this.sqlSessionProxy.selectCursor(statement);
}
public <T> Cursor<T> selectCursor(String statement, Object parameter) {
return this.sqlSessionProxy.selectCursor(statement, parameter);
}
public <T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds) {
return this.sqlSessionProxy.selectCursor(statement, parameter, rowBounds);
}
public <E> List<E> selectList(String statement) {
return this.sqlSessionProxy.selectList(statement);
}
public <E> List<E> selectList(String statement, Object parameter) {
return this.sqlSessionProxy.selectList(statement, parameter);
}
public <E> List<E> selectList(String statement, Object parameter, RowBounds rowBounds) {
return this.sqlSessionProxy.selectList(statement, parameter, rowBounds);
}
public void select(String statement, ResultHandler handler) {
this.sqlSessionProxy.select(statement, handler);
}
public void select(String statement, Object parameter, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, handler);
}
public void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler) {
this.sqlSessionProxy.select(statement, parameter, rowBounds, handler);
}
public int insert(String statement) {
return this.sqlSessionProxy.insert(statement);
}
public int insert(String statement, Object parameter) {
return this.sqlSessionProxy.insert(statement, parameter);
}
public int update(String statement) {
return this.sqlSessionProxy.update(statement);
}
public int update(String statement, Object parameter) {
return this.sqlSessionProxy.update(statement, parameter);
}
public int delete(String statement) {
return this.sqlSessionProxy.delete(statement);
}
public int delete(String statement, Object parameter) {
return this.sqlSessionProxy.delete(statement, parameter);
}
public <T> T getMapper(Class<T> type) {
return this.getConfiguration().getMapper(type, this);
}
public Connection getConnection() {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot get connection. No managed session is started.");
} else {
return sqlSession.getConnection();
}
}
public void clearCache() {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot clear the cache. No managed session is started.");
} else {
sqlSession.clearCache();
}
}
public void commit() {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot commit. No managed session is started.");
} else {
sqlSession.commit();
}
}
public void commit(boolean force) {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot commit. No managed session is started.");
} else {
sqlSession.commit(force);
}
}
public void rollback() {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot rollback. No managed session is started.");
} else {
sqlSession.rollback();
}
}
public void rollback(boolean force) {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot rollback. No managed session is started.");
} else {
sqlSession.rollback(force);
}
}
public List<BatchResult> flushStatements() {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot rollback. No managed session is started.");
} else {
return sqlSession.flushStatements();
}
}
public void close() {
SqlSession sqlSession = (SqlSession)this.localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot close. No managed session is started.");
} else {
try {
sqlSession.close();
} finally {
this.localSqlSession.set((Object)null);
}
}
}
private class SqlSessionInterceptor implements InvocationHandler {
public SqlSessionInterceptor() {
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
SqlSession sqlSession = (SqlSession)SqlSessionManager.this.localSqlSession.get();
if (sqlSession != null) {
try {
return method.invoke(sqlSession, args);
} catch (Throwable var12) {
throw ExceptionUtil.unwrapThrowable(var12);
}
} else {
SqlSession autoSqlSession = SqlSessionManager.this.openSession();
Object var7;
try {
Object result = method.invoke(autoSqlSession, args);
autoSqlSession.commit();
var7 = result;
} catch (Throwable var13) {
autoSqlSession.rollback();
throw ExceptionUtil.unwrapThrowable(var13);
} finally {
autoSqlSession.close();
}
return var7;
}
}
}
}
6. 下面讲SqlSession和Mapper的关系 放到2去
public class RowBounds { //作用2个:分页和
public static final int NO_ROW_OFFSET = 0;
public static final int NO_ROW_LIMIT = 2147483647;
public static final RowBounds DEFAULT = new RowBounds();
private int offset;
private int limit;
public RowBounds() {
this.offset = 0;
this.limit = 2147483647;
}
public RowBounds(int offset, int limit) {
this.offset = offset;
this.limit = limit;
}
public int getOffset() {
return this.offset;
}
public int getLimit() {
return this.limit;
}
}