本文,我们简单看一下jpa调用sql时的代码主流程大概是什么样子的
1.首先根据启动流程我们看到最终实际与数据库交互的时EntityMananger的实现类,其具体实现类有SessionImpl(当然此类以被各种加强),但核心入口还是在这里,如查询方法进行list方法,参数1为就是我们配置的sql语句,参数二为sql参数的包装,先看下代码,在看下debug后的参数列表:
@Override
public List list(String query, QueryParameters queryParameters) throws HibernateException {
checkOpenOrWaitingForAutoClose();
checkTransactionSynchStatus();
queryParameters.validateParameters();
//1.重点创建对应HQL执行Plan
HQLQueryPlan plan = queryParameters.getQueryPlan();
if ( plan == null ) {
plan = getQueryPlan( query, false );
}
autoFlushIfRequired( plan.getQuerySpaces() );
List results = Collections.EMPTY_LIST;
boolean success = false;
dontFlushFromFind++; //stops flush being called multiple times if this method is recursively called
try {
results = plan.performList( queryParameters, this );
success = true;
}
finally {
dontFlushFromFind--;
afterOperation( success );
delayedAfterCompletion();
}
return results;
}
一起看下参数列表:
-
sql为
image.png -
对应的参数列表为TypedValue类的对象(和mybatis处理基本一样),:
image.png
继续往下走,就会找到HQLQueryPlan类,此类为HQL语句处理的然后向后转为sql的执行类,此时重点创建hibernate对应的Hql执行类,然后继续执行results = plan.performList( queryParameters, this ) 方法,进入处理方法,会调用QueryTranslatorImpl类的list方法进行hql的slq解析(此时已进入hibernate的代码逻辑),让我们一起学习一下:
public List list(SharedSessionContractImplementor session, QueryParameters queryParameters)
throws HibernateException {
// Delegate to the QueryLoader...
errorIfDML();
final QueryNode query = (QueryNode) sqlAst;
//1.是否有查询行数限制
final boolean hasLimit = queryParameters.getRowSelection() != null && queryParameters.getRowSelection().definesLimits();
final boolean needsDistincting = (
query.getSelectClause().isDistinct() ||
getEntityGraphQueryHint() != null ||
hasLimit )
&& containsCollectionFetches();
QueryParameters queryParametersToUse;
if ( hasLimit && containsCollectionFetches() ) {
boolean fail = session.getFactory().getSessionFactoryOptions().isFailOnPaginationOverCollectionFetchEnabled();
if (fail) {
throw new HibernateException("firstResult/maxResults specified with collection fetch. " +
"In memory pagination was about to be applied. " +
"Failing because 'Fail on pagination over collection fetch' is enabled.");
}
else {
LOG.firstOrMaxResultsSpecifiedWithCollectionFetch();
}
RowSelection selection = new RowSelection();
selection.setFetchSize( queryParameters.getRowSelection().getFetchSize() );
selection.setTimeout( queryParameters.getRowSelection().getTimeout() );
queryParametersToUse = queryParameters.createCopyUsing( selection );
}
else {
queryParametersToUse = queryParameters;
}
//2.调用QueryLoader进行sql执行
List results = queryLoader.list( session, queryParametersToUse );
if ( needsDistincting ) {
int includedCount = -1;
// NOTE : firstRow is zero-based
int first = !hasLimit || queryParameters.getRowSelection().getFirstRow() == null
? 0
: queryParameters.getRowSelection().getFirstRow();
int max = !hasLimit || queryParameters.getRowSelection().getMaxRows() == null
? -1
: queryParameters.getRowSelection().getMaxRows();
List tmp = new ArrayList();
IdentitySet distinction = new IdentitySet();
for ( final Object result : results ) {
if ( !distinction.add( result ) ) {
continue;
}
includedCount++;
if ( includedCount < first ) {
continue;
}
tmp.add( result );
// NOTE : ( max - 1 ) because first is zero-based while max is not...
if ( max >= 0 && ( includedCount - first ) >= ( max - 1 ) ) {
break;
}
}
results = tmp;
}
return results;
}
我们发现,最终调用了QueryLoader类进行实际调用,此类对应类我们每一个方法对应上文的Query实体,看下代码这里还有些缓存处理,我们暂且不管(不是本文重点)
protected List list(
final SharedSessionContractImplementor session,
final QueryParameters queryParameters,
final Set<Serializable> querySpaces,
final Type[] resultTypes) throws HibernateException {
final boolean cacheable = factory.getSessionFactoryOptions().isQueryCacheEnabled() &&
queryParameters.isCacheable();
if ( cacheable ) {
return listUsingQueryCache( session, queryParameters, querySpaces, resultTypes );
}
else {
return listIgnoreQueryCache( session, queryParameters );
}
}
通过listIgnoreQueryCache方法最终调用到doList方法,doList像个模版方法到样子,我们也发现的确是模版方法,此时进入了Loader类中.
在Loader类中,里边层层包装,最后调用executeQueryStatement方法,此方法中,我们看到了熟悉的jdbc类PreparedStatement(放sql注入),此类也将会实际执行转化后的sql语句
protected SqlStatementWrapper executeQueryStatement(
String sqlStatement,
QueryParameters queryParameters,
boolean scroll,
List<AfterLoadAction> afterLoadActions,
SharedSessionContractImplementor session) throws SQLException {
// Processing query filters.
queryParameters.processFilters( sqlStatement, session );
// Applying LIMIT clause.
final LimitHandler limitHandler = getLimitHandler(
queryParameters.getRowSelection()
);
//1.sql预处理,添加hql相关别名
String sql = limitHandler.processSql( queryParameters.getFilteredSQL(), queryParameters.getRowSelection() );
// Adding locks and comments.
sql = preprocessSQL( sql, queryParameters, getFactory(), afterLoadActions );
/2.生成sql对应PreparedStatement,此类有防sql注入的特性
final PreparedStatement st = prepareQueryStatement( sql, queryParameters, limitHandler, scroll, session );
final ResultSet rs;
if( queryParameters.isCallable() && isTypeOf( st, CallableStatement.class ) ) {
final CallableStatement cs = st.unwrap( CallableStatement.class );
rs = getResultSet(
cs,
queryParameters.getRowSelection(),
limitHandler,
queryParameters.hasAutoDiscoverScalarTypes(),
session
);
}
else {
//3.获取结果集
rs = getResultSet(
st,
queryParameters.getRowSelection(),
limitHandler,
queryParameters.hasAutoDiscoverScalarTypes(),
session
);
}
//4.结果包装
return new SqlStatementWrapper(
st,
rs
);
}
好了,此方法放回到类中将包含我们所需要到查询结果,只需层层上交最后交给对应到使用放即可.
总结下:
- SessionImpl类为入口,进行list查询操作
- 生成HQLQueryPlan,进行hibernate类操作
- plan.performList( queryParameters, this )调用QueryTranslatorImpl类调用每个dao方法对应Query类
- 下面在抽象类Loader中调用实际的相应一系列do方法,最后进入
- executeQueryStatement方法进行entity到sql的映射,
- 下面是熟悉的PreparedStatement等类的jdbc执行操作包装

