前面說到Java動態代理,Mybatis通過這種方式實現了我們通過getMapper方式得到的Dao接口,可以直接通過接口的沒有實現的方法來執行sql。
AuthUserDao mapper = session.getMapper(AuthUserDao.class);
getMapper方法到底做了什么。跟蹤getMapper方法,進入到 MapperProxyFactory 類的 newInstance(SqlSession sqlSession) 方法。
@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);
}
看過上一篇的例子,我們知道。最后是通過Proxy.newProxyInstance 來實現切入sql的。他的實現在MapperProxy的 invoke 方法里面。看下invoke方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(this, args); } final MapperMethod mapperMethod = cachedMapperMethod(method); return mapperMethod.execute(sqlSession, args); }
簡單來說,在invoke里面做了如下事情:
1. 通過我們調用的方法,如本例中的 selectAuthUserByName ,接口名來組合成語句。本例中是 com.mybatis.dao.AuthUserDao.selectAuthUserByName 。其實使用過sqlSession的selectOne(String statmet)之類的語句都知道。這個可以唯一定位到我們在sql映射文件中配置的sql語句
2. 通過返回值類型,定位到的語句的類型。確定最后應該執行的方法。是執行查詢、刪除、添加、修改等等。
看下mybatis的是如何做的:
public Object execute(SqlSession sqlSession, Object[] args) {
Object result;
if (SqlCommandType.INSERT == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.insert(command.getName(), param));
} else if (SqlCommandType.UPDATE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.update(command.getName(), param));
} else if (SqlCommandType.DELETE == command.getType()) {
Object param = method.convertArgsToSqlCommandParam(args);
result = rowCountResult(sqlSession.delete(command.getName(), param));
} else if (SqlCommandType.SELECT == command.getType()) {
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 {
Object param = method.convertArgsToSqlCommandParam(args);
result = sqlSession.selectOne(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;
}
可以看到的是,他是通過我們在sql配置文件中的語句類型來判斷是執行哪種操作。然后通過返回類型來確定查詢是查一條還是查多條記錄。最后這種操作的方式,也是回歸到了sqlSession中的CRUD的操作的方法。
下面看下,一條sql語句到底是怎么執行的?我們知道Mybatis其實是對JDBC的一個封裝。假如我執行
session.update("com.mybatis.dao.AuthUserDao.updateAuthUserEmailByName", test@email.com);
語句,追蹤下來,Executor、 BaseStatementHandler等等。在 SimpleExecutor 中有如下代碼:
public int doUpdate(MappedStatement ms, Object parameter) throws SQLException {
Statement stmt = null;
try {
Configuration configuration = ms.getConfiguration();
StatementHandler handler = configuration.newStatementHandler(this, ms, parameter, RowBounds.DEFAULT, null, null);
stmt = prepareStatement(handler, ms.getStatementLog());
return handler.update(stmt);
} finally {
closeStatement(stmt);
}
}
1. 首先獲取相關配置信息,這個在初始化時,從配置文件中解析而來
2. 新建了一個handler
3. 做了執行statement之前的准備工作。看看准備了些什么,跟蹤代碼,最后進入了DataSource類的doGetConnection方法,該方法做如下操作:
private Connection doGetConnection(Properties properties) throws SQLException {
initializeDriver();
Connection connection = DriverManager.getConnection(url, properties);
configureConnection(connection);
return connection;
}
private synchronized void initializeDriver() throws SQLException {
if (!registeredDrivers.containsKey(driver)) {
Class<?> driverType;
try {
if (driverClassLoader != null) {
driverType = Class.forName(driver, true, driverClassLoader);
} else {
driverType = Resources.classForName(driver);
}
// DriverManager requires the driver to be loaded via the system ClassLoader.
// http://www.kfu.com/~nsayer/Java/dyn-jdbc.html
Driver driverInstance = (Driver)driverType.newInstance();
DriverManager.registerDriver(new DriverProxy(driverInstance));
registeredDrivers.put(driver, driverInstance);
} catch (Exception e) {
throw new SQLException("Error setting driver on UnpooledDataSource. Cause: " + e);
}
}
}
原來是通過prepareStatement 來執行了 我們初始化jdbc的操作。Class.forName DriverManager.getConnection. 這兩步是在這里面完成的。
4. 將執行sql的部分交給handler
繼續跟蹤handler 可以看到SimpleStatementHandler 中。如下執行這個update語句
public int update(Statement statement)
throws SQLException {
String sql = boundSql.getSql();
Object parameterObject = boundSql.getParameterObject();
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
int rows;
if (keyGenerator instanceof Jdbc3KeyGenerator) {
statement.execute(sql, Statement.RETURN_GENERATED_KEYS);
rows = statement.getUpdateCount();
keyGenerator.processAfter(executor, mappedStatement, statement, parameterObject);
} else if (keyGenerator instanceof SelectKeyGenerator) {
statement.execute(sql);
rows = statement.getUpdateCount();
keyGenerator.processAfter(executor, mappedStatement, statement, parameterObject);
} else {
statement.execute(sql);
rows = statement.getUpdateCount();
}
return rows;
}
這邊就完成了statement的操作,整個過程就是我們Jdbc的過程。原來真的就是對JDBC的簡單封裝。
其實Mybatis的整個執行過程,理解起來分為如下幾個過程:
1. 加載配置文件
2. 解析配置文件,從配置文件中解析出來 datasource、mapper文件、事務配置等等。將配置信息保存在對象內
3. 調用相關語句,執行sql。在執行的方法中分別完成JDBC的一系列操作。