}
// If refreshing, maintain object identity;
// otherwise construct a new aggregate object.
Object aggregate = null;
ClassDescriptor descriptor = getReferenceDescriptor();
boolean refreshing = true;
if (descriptor.hasInheritance()) {
Class newAggregateClass = descriptor.getInheritancePolicy().classFromRow(databaseRow, session);
descriptor = getReferenceDescriptor(newAggregateClass, session);
if (joinManager.getBaseQuery().shouldRefreshIdentityMapResult()) {
aggregate = getMatchingAttributeValueFromObject(databaseRow, targetObject, session, descriptor);
if ((aggregate != null) && (aggregate.getClass() != newAggregateClass)) {
// if the class has changed out from underneath us, we cannot preserve object identity
// build a new instance of the *new* class
aggregate = descriptor.getObjectBuilder().buildNewInstance();
refreshing = false;
}
}
} else {
if (joinManager.getBaseQuery().shouldRefreshIdentityMapResult()) {
aggregate = getMatchingAttributeValueFromObject(databaseRow, targetObject, session, descriptor);
}
}
if (aggregate == null) {
aggregate = descriptor.getObjectBuilder().buildNewInstance();
refreshing = false;
}
ObjectBuildingQuery nestedQuery = joinManager.getBaseQuery();
nestedQuery.setSession(session); //ensure the correct session is set on the query.
if (joinManager.getBaseQuery().isObjectLevelReadQuery()){
if (joinManager.isAttributeJoined(getDescriptor(), getAttributeName()) ){
// A nested query must be built to pass to the descriptor that looks like the real query execution would.
nestedQuery = (ObjectLevelReadQuery)((ObjectLevelReadQuery)joinManager.getBaseQuery()).deepClone();
// Must cascade the nested partial/join expression and filter the nested ones.
((ObjectLevelReadQuery)nestedQuery).getJoinedAttributeManager().setJoinedAttributeExpressions_(extractNestedExpressions(joinManager.getJoinedAttributeExpressions(), joinManager.getBaseExpressionBuilder(), false));
nestedQuery.setDescriptor(descriptor);
}
}
if (buildShallowOriginal) {
descriptor.getObjectBuilder().buildAttributesIntoShallowObject(aggregate, databaseRow, nestedQuery);
} else if (session.isUnitOfWork()) {
descriptor.getObjectBuilder().buildAttributesIntoWorkingCopyClone(aggregate, nestedQuery, joinManager, databaseRow, (UnitOfWorkImpl)session, refreshing);
} else {
descriptor.getObjectBuilder().buildAttributesIntoObject(aggregate, databaseRow, nestedQuery, joinManager, refreshing);
}
return aggregate;
}