mybatis代码
来源:互联网 发布:erp系统网络架构图 编辑:程序博客网 时间:2024/06/06 09:40
http://my.oschina.net/zimingforever/blog/112591
mybatis的入门可以参考这里:http://my.oschina.net/zimingforever/blog/111907
之前把mybaits的源码简单的看了下,这篇博客主要会跟踪一下mybatis进行一次查询时的代码流。
1 先读取mybatis的配置文件,然后通过sqlsessionfactorybuider通过配置文件获取sqlsessionFactory
1
2
3
String resource =
"org/mybatis/example/mybatis-config.xml"
;
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory =
new
SqlSessionFactoryBuilder().build(inputStream);
2 defaultsqlSessionFactory调用了openSession()获得到一个Sqlsession
1
SqlSession session = sqlSessionFactory.openSession();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public
SqlSession openSession() {
return
openSessionFromDataSource(configuration.getDefaultExecutorType(),
null
,
false
);
}
private
SqlSession openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level,
boolean
autoCommit) {
Transaction tx =
null
;
try
{
final
Environment environment = configuration.getEnvironment();
final
TransactionFactory transactionFactory = getTransactionFactoryFromEnvironment(environment);
tx = transactionFactory.newTransaction(environment.getDataSource(), level, autoCommit);
final
Executor executor = configuration.newExecutor(tx, execType, autoCommit);
return
new
DefaultSqlSession(configuration, executor);
}
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();
}
}
其中的configuration.getDefaultExecutorType()获取到的是simple,这里获取一个executor,这个executor是simpleExecutor
这里的sqlsession是DefaultSqlSession
3 调用sqlsession的selectOne方法
1
Blog blog = (Blog) session.selectOne(
"org.mybatis.example.BlogMapper.selectBlog"
,
1
);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public
<T> T selectOne(String statement, Object parameter) {
// Popular vote was to return null on 0 results and throw exception on too many.
List<T> list =
this
.<T>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, RowBounds rowBounds) {
try
{
MappedStatement ms = configuration.getMappedStatement(statement);
List<E> result = executor.<E>query(ms, wrapCollection(parameter), rowBounds, Executor.NO_RESULT_HANDLER);
return
result;
}
catch
(Exception e) {
throw
ExceptionFactory.wrapException(
"Error querying database. Cause: "
+ e, e);
}
finally
{
ErrorContext.instance().reset();
}
}
其中selectone调用的是selectlist()方法,其中调用了executor的query方法,这里的executor是simpleExecutor其继承BaseExecutor
其中BaseExecuotr中又有如下方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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++;
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();
}
deferredLoads.clear();
// issue #601
if
(configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
clearLocalCache();
// issue #482
}
}
return
list;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}
其中的doquery在simpleExecutor实现为:
1
2
3
4
5
6
7
8
9
10
11
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 handler = configuration.newStatementHandler(
this
, ms, parameter, rowBounds, resultHandler, boundSql);
stmt = prepareStatement(handler, ms.getStatementLog());
return
handler.<E>query(stmt, resultHandler);
}
finally
{
closeStatement(stmt);
}
}
1
2
3
4
5
6
7
private
Statement prepareStatement(StatementHandler handler, Log statementLog)
throws
SQLException {
Statement stmt;
Connection connection = getConnection(statementLog);
stmt = handler.prepare(connection);
handler.parameterize(stmt);
return
stmt;
}
其中的hander为preparedstatementHandler,其query方法实现为:、
1
2
3
4
5
public
<E> List<E> query(Statement statement, ResultHandler resultHandler)
throws
SQLException {
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
return
resultSetHandler.<E> handleResultSets(ps);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public
List<Object> handleResultSets(Statement stmt)
throws
SQLException {
final
List<Object> multipleResults =
new
ArrayList<Object>();
final
List<ResultMap> resultMaps = mappedStatement.getResultMaps();
int
resultMapCount = resultMaps.size();
int
resultSetCount =
0
;
ResultSet rs = stmt.getResultSet();
while
(rs ==
null
) {
// move forward to get the first resultset in case the driver
// doesn't return the resultset as the first result (HSQLDB 2.1)
if
(stmt.getMoreResults()) {
rs = stmt.getResultSet();
}
else
{
if
(stmt.getUpdateCount() == -
1
) {
// no more results. Must be no resultset
break
;
}
}
}
validateResultMapsCount(rs, resultMapCount);
while
(rs !=
null
&& resultMapCount > resultSetCount) {
final
ResultMap resultMap = resultMaps.get(resultSetCount);
ResultColumnCache resultColumnCache =
new
ResultColumnCache(rs.getMetaData(), configuration);
handleResultSet(rs, resultMap, multipleResults, resultColumnCache);
rs = getNextResultSet(stmt);
cleanUpAfterHandlingResultSet();
resultSetCount++;
}
return
collapseSingleResultList(multipleResults);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
protected
void
handleResultSet(ResultSet rs, ResultMap resultMap, List<Object> multipleResults, ResultColumnCache resultColumnCache)
throws
SQLException {
try
{
if
(resultHandler ==
null
) {
DefaultResultHandler defaultResultHandler =
new
DefaultResultHandler(objectFactory);
handleRowValues(rs, resultMap, defaultResultHandler, rowBounds, resultColumnCache);
multipleResults.add(defaultResultHandler.getResultList());
}
else
{
handleRowValues(rs, resultMap, resultHandler, rowBounds, resultColumnCache);
}
}
finally
{
closeResultSet(rs);
// issue #228 (close resultsets)
}
}
1
2
3
4
5
6
7
8
9
protected
void
handleRowValues(ResultSet rs, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultColumnCache resultColumnCache)
throws
SQLException {
final
DefaultResultContext resultContext =
new
DefaultResultContext();
skipRows(rs, rowBounds);
while
(shouldProcessMoreRows(rs, resultContext, rowBounds)) {
final
ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rs, resultMap,
null
);
Object rowValue = getRowValue(rs, discriminatedResultMap,
null
, resultColumnCache);
callResultHandler(resultHandler, resultContext, rowValue);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
protected
Object getRowValue(ResultSet rs, ResultMap resultMap, CacheKey rowKey, ResultColumnCache resultColumnCache)
throws
SQLException {
final
ResultLoaderMap lazyLoader = instantiateResultLoaderMap();
Object resultObject = createResultObject(rs, resultMap, lazyLoader,
null
, resultColumnCache);
if
(resultObject !=
null
&& !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) {
final
MetaObject metaObject = configuration.newMetaObject(resultObject);
boolean
foundValues = resultMap.getConstructorResultMappings().size() >
0
;
if
(shouldApplyAutomaticMappings(resultMap, !AutoMappingBehavior.NONE.equals(configuration.getAutoMappingBehavior()))) {
final
List<String> unmappedColumnNames = resultColumnCache.getUnmappedColumnNames(resultMap,
null
);
foundValues = applyAutomaticMappings(rs, unmappedColumnNames, metaObject,
null
, resultColumnCache) || foundValues;
}
final
List<String> mappedColumnNames = resultColumnCache.getMappedColumnNames(resultMap,
null
);
foundValues = applyPropertyMappings(rs, resultMap, mappedColumnNames, metaObject, lazyLoader,
null
) || foundValues;
foundValues = (lazyLoader !=
null
&& lazyLoader.size() >
0
) || foundValues;
resultObject = foundValues ? resultObject :
null
;
return
resultObject;
}
return
resultObject;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
protected
boolean
applyAutomaticMappings(ResultSet rs, List<String> unmappedColumnNames, MetaObject metaObject, String columnPrefix, ResultColumnCache resultColumnCache)
throws
SQLException {
boolean
foundValues =
false
;
for
(String columnName : unmappedColumnNames) {
String propertyName = columnName;
if
(columnPrefix !=
null
&& columnPrefix.length() >
0
) {
// When columnPrefix is specified,
// ignore columns without the prefix.
if
(columnName.startsWith(columnPrefix)) {
propertyName = columnName.substring(columnPrefix.length());
}
else
{
continue
;
}
}
final
String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
if
(property !=
null
) {
final
Class<?> propertyType = metaObject.getSetterType(property);
if
(typeHandlerRegistry.hasTypeHandler(propertyType)) {
final
TypeHandler<?> typeHandler = resultColumnCache.getTypeHandler(propertyType, columnName);
final
Object value = typeHandler.getResult(rs, columnName);
if
(value !=
null
|| configuration.isCallSettersOnNulls()) {
// issue #377, call setter on nulls
metaObject.setValue(property, value);
foundValues =
true
;
}
}
}
}
return
foundValues;
}
0 0
- mybatis代码
- MyBatis代码
- MyBatis Generator/MyBatis代码生成器。
- mybatis代码生成实例
- MyBatis-Generator 代码生成
- mybatis代码生成器
- MyBatis 分页代码实现
- mybatis-generator 代码生成
- MyBatis代码自动生成
- MyBatis代码生成工具
- [Mybatis]代码生成工具
- mybatis 自动生成代码
- mybatis代码配置文件记录
- Mybatis自动生成代码
- Mybatis自动生成代码
- MyBatis代码自动生成
- Mybatis 代码自动生成
- Mybatis/ibatis代码生成
- 电脑需要重装系统的详细汇总
- mybatis入门
- 3.2创建工程批处理文件
- 从源代码分析Android-Universal-Image-Loader的缓存处理机制2
- 学习Unity3D第十一天之方法重载。
- mybatis代码
- 内网环境中使用DVD安装文件配置本地yum源
- SVN服务器的搭建
- unity3D——参数
- Centos6.4安装Mono3.10+jexus
- Android-Universal-Image-Loader 的使用说明
- jbpm的表结构以及六大服务
- Java对象初始化详解
- Blogilo:Ubuntu下“wlw”