/** Get the names of all entities */
 @Override
 public String[] getEntityNames() {
   if (sessionFactory == null) {
     return ArrayHelper.toStringArray(entityStatistics.keySet());
   } else {
     return ArrayHelper.toStringArray(sessionFactory.getAllClassMetadata().keySet());
   }
 }
 /** Get all second-level cache region names */
 @Override
 public String[] getSecondLevelCacheRegionNames() {
   if (sessionFactory == null) {
     return ArrayHelper.toStringArray(secondLevelCacheStatistics.keySet());
   } else {
     return ArrayHelper.toStringArray(sessionFactory.getAllSecondLevelCacheRegions().keySet());
   }
 }
 /** Get the names of all collection roles */
 @Override
 public String[] getCollectionRoleNames() {
   if (sessionFactory == null) {
     return ArrayHelper.toStringArray(collectionStatistics.keySet());
   } else {
     return ArrayHelper.toStringArray(sessionFactory.getAllCollectionMetadata().keySet());
   }
 }
  protected void initPersisters(
      final List associations,
      final LockOptions lockOptions,
      final AssociationInitCallback callback)
      throws MappingException {
    final int joins = countEntityPersisters(associations);
    final int collections = countCollectionPersisters(associations);

    collectionOwners = collections == 0 ? null : new int[collections];
    collectionPersisters = collections == 0 ? null : new CollectionPersister[collections];
    collectionSuffixes = BasicLoader.generateSuffixes(joins + 1, collections);

    this.lockOptions = lockOptions;

    persisters = new Loadable[joins];
    aliases = new String[joins];
    owners = new int[joins];
    ownerAssociationTypes = new EntityType[joins];
    lockModeArray = ArrayHelper.fillArray(lockOptions.getLockMode(), joins);

    int i = 0;
    int j = 0;
    Iterator iter = associations.iterator();
    while (iter.hasNext()) {
      final OuterJoinableAssociation oj = (OuterJoinableAssociation) iter.next();
      if (!oj.isCollection()) {

        persisters[i] = (Loadable) oj.getJoinable();
        aliases[i] = oj.getRHSAlias();
        owners[i] = oj.getOwner(associations);
        ownerAssociationTypes[i] = (EntityType) oj.getJoinableType();
        callback.associationProcessed(oj, i);
        i++;

      } else {

        QueryableCollection collPersister = (QueryableCollection) oj.getJoinable();
        if (oj.getJoinType() == JoinType.LEFT_OUTER_JOIN && !oj.hasRestriction()) {
          // it must be a collection fetch
          collectionPersisters[j] = collPersister;
          collectionOwners[j] = oj.getOwner(associations);
          j++;
        }

        if (collPersister.isOneToMany()) {
          persisters[i] = (Loadable) collPersister.getElementPersister();
          aliases[i] = oj.getRHSAlias();
          callback.associationProcessed(oj, i);
          i++;
        }
      }
    }

    if (ArrayHelper.isAllNegative(owners)) owners = null;
    if (collectionOwners != null && ArrayHelper.isAllNegative(collectionOwners)) {
      collectionOwners = null;
    }
  }
 public String[] getSynchronizedTableNameClosure() {
   if (isRoot()) {
     return getSynchronizedTableNames();
   }
   return ArrayHelper.join(
       superEntityBinding.getSynchronizedTableNameClosure(), getSynchronizedTableNames());
 }
Exemple #6
0
  public static int[] locateUnquoted(String string, char character) {
    if ('\'' == character) {
      throw new IllegalArgumentException("Unquoted count of quotes is invalid");
    }
    if (string == null) {
      return new int[0];
    }

    ArrayList locations = new ArrayList(20);

    // Impl note: takes advantage of the fact that an escpaed single quote
    // embedded within a quote-block can really be handled as two seperate
    // quote-blocks for the purposes of this method...
    int stringLength = string.length();
    boolean inQuote = false;
    for (int indx = 0; indx < stringLength; indx++) {
      char c = string.charAt(indx);
      if (inQuote) {
        if ('\'' == c) {
          inQuote = false;
        }
      } else if ('\'' == c) {
        inQuote = true;
      } else if (c == character) {
        locations.add(indx);
      }
    }
    return ArrayHelper.toIntArray(locations);
  }
 public SecondaryTable[] getEntitiesSecondaryTableClosure() {
   if (!subEntityBindings.isEmpty()) {
     return ArrayHelper.join(getSecondaryTableClosure(), getSubEntitySecondaryTables());
   } else {
     return getSecondaryTableClosure();
   }
 }
 /**
  * Returns sub-EntityBinding objects in a special 'order', most derived subclasses first.
  * Specifically, the sub-entity bindings follow a depth-first, post-order traversal
  *
  * <p>Note that the returned value excludes this entity binding.
  *
  * @return sub-entity bindings ordered by those entity bindings that are most derived.
  */
 public EntityBinding[] getPostOrderSubEntityBindingClosure() {
   EntityBinding[] results = new EntityBinding[0];
   if (subEntityBindings.isEmpty()) {
     return results;
   }
   for (EntityBinding subEntityBinding : subEntityBindings) {
     EntityBinding[] subSubEntityBindings = subEntityBinding.getPostOrderSubEntityBindingClosure();
     results = ArrayHelper.join(results, subSubEntityBindings);
   }
   if (!subEntityBindings.isEmpty()) {
     results =
         ArrayHelper.join(
             results, subEntityBindings.toArray(new EntityBinding[subEntityBindings.size()]));
   }
   return results;
 }
  @Override
  public void nullSafeSet(
      PreparedStatement st, Object value, int begin, boolean[] settable, SessionImplementor session)
      throws HibernateException, SQLException {

    Object[] subvalues = nullSafeGetValues(value, entityMode);

    int loc = 0;
    for (int i = 0; i < propertySpan; i++) {
      int len = propertyTypes[i].getColumnSpan(session.getFactory());
      //noinspection StatementWithEmptyBody
      if (len == 0) {
        // noop
      } else if (len == 1) {
        if (settable[loc]) {
          propertyTypes[i].nullSafeSet(st, subvalues[i], begin, session);
          begin++;
        }
      } else {
        boolean[] subsettable = new boolean[len];
        System.arraycopy(settable, loc, subsettable, 0, len);
        propertyTypes[i].nullSafeSet(st, subvalues[i], begin, subsettable, session);
        begin += ArrayHelper.countTrue(subsettable);
      }
      loc += len;
    }
  }
  @Override
  public Object hydrate(
      final ResultSet rs,
      final String[] names,
      final SessionImplementor session,
      final Object owner)
      throws HibernateException, SQLException {

    int begin = 0;
    boolean notNull = false;
    Object[] values = new Object[propertySpan];
    for (int i = 0; i < propertySpan; i++) {
      int length = propertyTypes[i].getColumnSpan(session.getFactory());
      String[] range = ArrayHelper.slice(names, begin, length); // cache this
      Object val = propertyTypes[i].hydrate(rs, range, session, owner);
      if (val == null) {
        if (isKey) {
          return null; // different nullability rules for pk/fk
        }
      } else {
        notNull = true;
      }
      values[i] = val;
      begin += length;
    }

    return notNull ? values : null;
  }
  public QueryParameters getQueryParameters() {
    LockOptions lockOptions = new LockOptions();
    RowSelection selection = new RowSelection();
    selection.setFirstRow(rootCriteria.getFirstResult());
    selection.setMaxRows(rootCriteria.getMaxResults());
    selection.setTimeout(rootCriteria.getTimeout());
    selection.setFetchSize(rootCriteria.getFetchSize());
    final Map<String, LockMode> lockModeMap = rootCriteria.getLockModes();
    for (final String key : lockModeMap.keySet()) {
      final Criteria subcriteria = getAliasedCriteria(key);
      lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lockModeMap.get(key));
    }
    final List<Object> values = new ArrayList<Object>();
    final List<Type> types = new ArrayList<Type>();
    final Iterator<CriteriaImpl.Subcriteria> subcriteriaIterator =
        rootCriteria.iterateSubcriteria();
    while (subcriteriaIterator.hasNext()) {
      CriteriaImpl.Subcriteria subcriteria = subcriteriaIterator.next();
      LockMode lm = subcriteria.getLockMode();
      if (lm != null) {
        lockOptions.setAliasSpecificLockMode(getSQLAlias(subcriteria), lm);
      }
      if (subcriteria.getWithClause() != null) {
        TypedValue[] tv = subcriteria.getWithClause().getTypedValues(subcriteria, this);
        for (TypedValue aTv : tv) {
          values.add(aTv.getValue());
          types.add(aTv.getType());
        }
      }
    }

    // Type and value gathering for the WHERE clause needs to come AFTER lock mode gathering,
    // because the lock mode gathering loop now contains join clauses which can contain
    // parameter bindings (as in the HQL WITH clause).
    Iterator<CriteriaImpl.CriterionEntry> iter = rootCriteria.iterateExpressionEntries();
    while (iter.hasNext()) {
      CriteriaImpl.CriterionEntry ce = iter.next();
      TypedValue[] tv = ce.getCriterion().getTypedValues(ce.getCriteria(), this);
      for (TypedValue aTv : tv) {
        values.add(aTv.getValue());
        types.add(aTv.getType());
      }
    }

    Object[] valueArray = values.toArray();
    Type[] typeArray = ArrayHelper.toTypeArray(types);
    return new QueryParameters(
        typeArray,
        valueArray,
        lockOptions,
        selection,
        rootCriteria.isReadOnlyInitialized(),
        (rootCriteria.isReadOnlyInitialized() && rootCriteria.isReadOnly()),
        rootCriteria.getCacheable(),
        rootCriteria.getCacheRegion(),
        rootCriteria.getComment(),
        rootCriteria.getQueryHints(),
        rootCriteria.isLookupByNaturalKey(),
        rootCriteria.getResultTransformer());
  }
 public boolean isInsertable() {
   // if the property mapping consists of all formulas,
   // make it insertable
   final boolean[] columnInsertability = value.getColumnInsertability();
   return insertable
       && (columnInsertability.length == 0 || !ArrayHelper.isAllFalse(columnInsertability));
 }
  public static void processDynamicFilterParameters(
      final String sqlFragment, final ParameterContainer container, final HqlSqlWalker walker) {
    if (walker.getEnabledFilters().isEmpty()
        && (!hasDynamicFilterParam(sqlFragment))
        && (!(hasCollectionFilterParam(sqlFragment)))) {
      return;
    }

    Dialect dialect = walker.getSessionFactoryHelper().getFactory().getDialect();
    String symbols =
        new StringBuffer()
            .append(ParserHelper.HQL_SEPARATORS)
            .append(dialect.openQuote())
            .append(dialect.closeQuote())
            .toString();
    StringTokenizer tokens = new StringTokenizer(sqlFragment, symbols, true);
    StringBuffer result = new StringBuffer();

    while (tokens.hasMoreTokens()) {
      final String token = tokens.nextToken();
      if (token.startsWith(ParserHelper.HQL_VARIABLE_PREFIX)) {
        final String filterParameterName = token.substring(1);
        final String[] parts = LoadQueryInfluencers.parseFilterParameterName(filterParameterName);
        final FilterImpl filter = (FilterImpl) walker.getEnabledFilters().get(parts[0]);
        final Object value = filter.getParameter(parts[1]);
        final Type type = filter.getFilterDefinition().getParameterType(parts[1]);
        final String typeBindFragment =
            StringHelper.join(
                ",",
                ArrayHelper.fillArray(
                    "?", type.getColumnSpan(walker.getSessionFactoryHelper().getFactory())));
        final String bindFragment =
            (value != null && Collection.class.isInstance(value))
                ? StringHelper.join(
                    ",", ArrayHelper.fillArray(typeBindFragment, ((Collection) value).size()))
                : typeBindFragment;
        result.append(bindFragment);
        container.addEmbeddedParameter(
            new DynamicFilterParameterSpecification(parts[0], parts[1], type));
      } else {
        result.append(token);
      }
    }

    container.setText(result.toString());
  }
 public SecondaryTable[] getSecondaryTableClosure() {
   if (isRoot()) {
     return secondaryTables.values().toArray(new SecondaryTable[secondaryTables.size()]);
   } else {
     return ArrayHelper.join(
         superEntityBinding.getSecondaryTableClosure(),
         secondaryTables.values().toArray(new SecondaryTable[secondaryTables.size()]));
   }
 }
 public AttributeBinding[] getNonIdAttributeBindingClosure() {
   // TODO: update size to account for joins
   if (isRoot()) {
     return internalGetNonIdAttributeBindings();
   } else {
     return ArrayHelper.join(
         superEntityBinding.getNonIdAttributeBindingClosure(),
         internalGetNonIdAttributeBindings());
   }
 }
 private EntityBinding[] getPreOrderSubEntityBindingClosure(
     boolean includeThis, EntityBinding[] results) {
   if (includeThis) {
     results = ArrayHelper.join(results, this);
   }
   for (EntityBinding subEntityBinding : subEntityBindings) {
     results = subEntityBinding.getPreOrderSubEntityBindingClosure(true, results);
   }
   return results;
 }
  @Override
  protected void autoDiscoverTypes(ResultSet rs) {
    try {
      Metadata metadata = new Metadata(getFactory(), rs);
      rowProcessor.prepareForAutoDiscovery(metadata);

      List<String> aliases = new ArrayList<String>();
      List<Type> types = new ArrayList<Type>();
      for (int i = 0; i < rowProcessor.columnProcessors.length; i++) {
        rowProcessor.columnProcessors[i].performDiscovery(metadata, types, aliases);
      }

      validateAliases(aliases);

      resultTypes = ArrayHelper.toTypeArray(types);
      transformerAliases = ArrayHelper.toStringArray(aliases);
    } catch (SQLException e) {
      throw new HibernateException("Exception while trying to autodiscover types.", e);
    }
  }
 @Override
 public int[] getNamedParameterLocs(String name) throws QueryException {
   Object loc = namedParameterBindPoints.get(name);
   if (loc == null) {
     throw new QueryException("Named parameter does not appear in Query: " + name, sql);
   }
   if (loc instanceof Integer) {
     return new int[] {(Integer) loc};
   } else {
     return ArrayHelper.toIntArray((List) loc);
   }
 }
 public SecondaryTable[] getSubEntitySecondaryTables() {
   SecondaryTable[] results = new SecondaryTable[0];
   for (EntityBinding eb : getPreOrderSubEntityBindingClosure()) {
     Collection<SecondaryTable> sts = eb.getSecondaryTables().values();
     int size = sts.size();
     if (size == 0) {
       continue;
     }
     results = ArrayHelper.join(results, sts.toArray(new SecondaryTable[size]));
   }
   return results;
 }
  public AttributeBinding[] getNonIdEntitiesAttributeBindingClosure() {
    AttributeBinding[] results = getNonIdAttributeBindingClosure();

    for (EntityBinding subEntityBinding : getPreOrderSubEntityBindingClosure()) {
      // only add attribute bindings declared for the subEntityBinding

      results = ArrayHelper.join(results, subEntityBinding.internalGetNonIdAttributeBindings());
      // TODO: if EntityBinding.attributeBindings() excludes joined attributes, then they need to be
      // added here
    }
    return results;
  }
Exemple #21
0
  public static void main(String... args) {
    int[] batchSizes = ArrayHelper.getBatchSizes(32);

    System.out.println("Forward ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    for (int i = 0; i < batchSizes.length; i++) {
      System.out.println("[" + i + "] -> " + batchSizes[i]);
    }

    System.out.println("Backward ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    for (int i = batchSizes.length - 1; i >= 0; i--) {
      System.out.println("[" + i + "] -> " + batchSizes[i]);
    }
  }
 /**
  * Gets the attribute bindings defined on this class, including the identifier attribute binding
  * and attribute bindings defined as part of a join.
  *
  * @return The attribute bindings.
  */
 public AttributeBinding[] getAttributeBindingClosure() {
   // TODO: update size to account for joins
   if (isRoot()) {
     return attributeBindingMapInternal()
         .values()
         .toArray(new AttributeBinding[attributeBindingMapInternal().size()]);
   } else {
     return ArrayHelper.join(
         superEntityBinding.getAttributeBindingClosure(),
         attributeBindingMapInternal()
             .values()
             .toArray(new AttributeBinding[attributeBindingMapInternal().size()]));
   }
 }
 @Override
 public int[] getNamedParameterLocs(String name) throws QueryException {
   Object o = namedParameters.get(name);
   if (o == null) {
     QueryException qe = new QueryException(ERROR_NAMED_PARAMETER_DOES_NOT_APPEAR + name);
     qe.setQueryString(queryString);
     throw qe;
   }
   if (o instanceof Integer) {
     return new int[] {((Integer) o).intValue()};
   } else {
     return ArrayHelper.toIntArray((ArrayList) o);
   }
 }
/*  69:    */   
/*  70:    */   public ParameterTranslationsImpl(List parameterSpecifications)
/*  71:    */   {
/*  72:107 */     int size = parameterSpecifications.size();
/*  73:108 */     List ordinalParameterList = new ArrayList();
/*  74:109 */     Map namedParameterMap = new HashMap();
/*  75:110 */     for (int i = 0; i < size; i++)
/*  76:    */     {
/*  77:111 */       ParameterSpecification spec = (ParameterSpecification)parameterSpecifications.get(i);
/*  78:112 */       if (PositionalParameterSpecification.class.isAssignableFrom(spec.getClass()))
/*  79:    */       {
/*  80:113 */         PositionalParameterSpecification ordinalSpec = (PositionalParameterSpecification)spec;
/*  81:114 */         ordinalParameterList.add(new ParameterInfo(i, ordinalSpec.getExpectedType()));
/*  82:    */       }
/*  83:116 */       else if (NamedParameterSpecification.class.isAssignableFrom(spec.getClass()))
/*  84:    */       {
/*  85:117 */         NamedParameterSpecification namedSpec = (NamedParameterSpecification)spec;
/*  86:118 */         Object paramHolder = (1NamedParamTempHolder)namedParameterMap.get(namedSpec.getName());
/*  87:119 */         if (paramHolder == null)
/*  88:    */         {
/*  89:120 */           paramHolder = new Object()
/*  90:    */           {
/*  91:    */             String name;
/*  92:    */             Type type;
/*  93:104 */             List positions = new ArrayList();
/*  94:120 */           };
/*  95:121 */           paramHolder.name = namedSpec.getName();
/*  96:122 */           paramHolder.type = namedSpec.getExpectedType();
/*  97:123 */           namedParameterMap.put(namedSpec.getName(), paramHolder);
/*  98:    */         }
/*  99:125 */         paramHolder.positions.add(Integer.valueOf(i));
/* 100:    */       }
/* 101:    */     }
/* 102:132 */     this.ordinalParameters = ((ParameterInfo[])ordinalParameterList.toArray(new ParameterInfo[ordinalParameterList.size()]));
/* 103:134 */     if (namedParameterMap.isEmpty())
/* 104:    */     {
/* 105:135 */       this.namedParameters = Collections.EMPTY_MAP;
/* 106:    */     }
/* 107:    */     else
/* 108:    */     {
/* 109:138 */       Map namedParametersBacking = new HashMap(namedParameterMap.size());
/* 110:139 */       Iterator itr = namedParameterMap.values().iterator();
/* 111:140 */       while (itr.hasNext())
/* 112:    */       {
/* 113:141 */         Object holder = (1NamedParamTempHolder)itr.next();
/* 114:142 */         namedParametersBacking.put(holder.name, new ParameterInfo(ArrayHelper.toIntArray(holder.positions), holder.type));
/* 115:    */       }
/* 116:147 */       this.namedParameters = Collections.unmodifiableMap(namedParametersBacking);
/* 117:    */     }
/* 118:    */   }
  public CriteriaJoinWalker(
      final OuterJoinLoadable persister,
      final CriteriaQueryTranslator translator,
      final SessionFactoryImplementor factory,
      final CriteriaImpl criteria,
      final String rootEntityName,
      final LoadQueryInfluencers loadQueryInfluencers,
      final String alias) {
    super(persister, factory, loadQueryInfluencers, alias);

    this.translator = translator;

    querySpaces = translator.getQuerySpaces();

    if (translator.hasProjection()) {
      initProjection(
          translator.getSelect(),
          translator.getWhereCondition(),
          translator.getOrderBy(),
          translator.getGroupBy(),
          LockOptions.NONE);
      resultTypes = translator.getProjectedTypes();
      userAliases = translator.getProjectedAliases();
      includeInResultRow = new boolean[resultTypes.length];
      Arrays.fill(includeInResultRow, true);
    } else {
      initAll(translator.getWhereCondition(), translator.getOrderBy(), LockOptions.NONE);
      // root entity comes last
      userAliasList.add(criteria.getAlias()); // root entity comes *last*
      resultTypeList.add(translator.getResultType(criteria));
      includeInResultRowList.add(true);
      userAliases = ArrayHelper.toStringArray(userAliasList);
      resultTypes = ArrayHelper.toTypeArray(resultTypeList);
      includeInResultRow = ArrayHelper.toBooleanArray(includeInResultRowList);
    }
  }
  /** For a composite element, add to a list of associations to be fetched by outerjoin */
  private void walkCompositeElementTree(
      final CompositeType compositeType,
      final String[] cols,
      final QueryableCollection persister,
      final String alias,
      final PropertyPath path,
      final int currentDepth)
      throws MappingException {

    Type[] types = compositeType.getSubtypes();
    String[] propertyNames = compositeType.getPropertyNames();
    int begin = 0;
    for (int i = 0; i < types.length; i++) {
      int length = types[i].getColumnSpan(getFactory());
      String[] lhsColumns = ArrayHelper.slice(cols, begin, length);

      if (types[i].isAssociationType()) {
        AssociationType associationType = (AssociationType) types[i];

        // simple, because we can't have a one-to-one or a collection
        // (or even a property-ref) in a composite-element:
        String[] aliasedLhsColumns = StringHelper.qualify(alias, lhsColumns);

        final PropertyPath subPath = path.append(propertyNames[i]);
        final boolean[] propertyNullability = compositeType.getPropertyNullability();
        final JoinType joinType =
            getJoinType(
                associationType,
                compositeType.getFetchMode(i),
                subPath,
                persister.getTableName(),
                lhsColumns,
                propertyNullability == null || propertyNullability[i],
                currentDepth,
                compositeType.getCascadeStyle(i));
        addAssociationToJoinTreeIfNecessary(
            associationType, aliasedLhsColumns, alias, subPath, currentDepth, joinType);
      } else if (types[i].isComponentType()) {
        final PropertyPath subPath = path.append(propertyNames[i]);
        walkCompositeElementTree(
            (CompositeType) types[i], lhsColumns, persister, alias, subPath, currentDepth);
      }
      begin += length;
    }
  }
  /**
   * @return the attribute bindings for this EntityBinding and all of its sub-EntityBinding,
   *     starting from the root of the hierarchy; includes the identifier and attribute bindings
   *     defined as part of a join.
   */
  public AttributeBinding[] getEntitiesAttributeBindingClosure() {
    AttributeBinding[] results = getAttributeBindingClosure();

    for (EntityBinding subEntityBinding : getPreOrderSubEntityBindingClosure()) {
      // only add attribute bindings declared for the subEntityBinding

      results =
          ArrayHelper.join(
              results,
              subEntityBinding
                  .attributeBindingMapInternal()
                  .values()
                  .toArray(
                      new AttributeBinding[subEntityBinding.attributeBindingMapInternal().size()]));
      // TODO: if EntityBinding.attributeBindings() excludes joined attributes, then they need to be
      // added here
    }
    return results;
  }
  public CustomLoader(CustomQuery customQuery, SessionFactoryImplementor factory) {
    super(factory);

    this.sql = customQuery.getSQL();
    this.querySpaces.addAll(customQuery.getQuerySpaces());
    this.namedParameterBindPoints = customQuery.getNamedParameterBindPoints();

    List entityPersisters = new ArrayList();
    List entityOwners = new ArrayList();
    List entityAliases = new ArrayList();

    List collectionPersisters = new ArrayList();
    List collectionOwners = new ArrayList();
    List collectionAliases = new ArrayList();

    List lockModes = new ArrayList();
    List resultColumnProcessors = new ArrayList();
    List nonScalarReturnList = new ArrayList();
    List resultTypes = new ArrayList();
    List specifiedAliases = new ArrayList();
    int returnableCounter = 0;
    boolean hasScalars = false;

    List includeInResultRowList = new ArrayList();

    Iterator itr = customQuery.getCustomQueryReturns().iterator();
    while (itr.hasNext()) {
      final Return rtn = (Return) itr.next();
      if (rtn instanceof ScalarReturn) {
        ScalarReturn scalarRtn = (ScalarReturn) rtn;
        resultTypes.add(scalarRtn.getType());
        specifiedAliases.add(scalarRtn.getColumnAlias());
        resultColumnProcessors.add(
            new ScalarResultColumnProcessor(
                StringHelper.unquote(scalarRtn.getColumnAlias(), factory.getDialect()),
                scalarRtn.getType()));
        includeInResultRowList.add(true);
        hasScalars = true;
      } else if (ConstructorReturn.class.isInstance(rtn)) {
        final ConstructorReturn constructorReturn = (ConstructorReturn) rtn;
        resultTypes.add(null); // this bit makes me nervous
        includeInResultRowList.add(true);
        hasScalars = true;

        ScalarResultColumnProcessor[] scalarProcessors =
            new ScalarResultColumnProcessor[constructorReturn.getScalars().length];
        int i = 0;
        for (ScalarReturn scalarReturn : constructorReturn.getScalars()) {
          scalarProcessors[i++] =
              new ScalarResultColumnProcessor(
                  StringHelper.unquote(scalarReturn.getColumnAlias(), factory.getDialect()),
                  scalarReturn.getType());
        }

        resultColumnProcessors.add(
            new ConstructorResultColumnProcessor(
                constructorReturn.getTargetClass(), scalarProcessors));
      } else if (rtn instanceof RootReturn) {
        RootReturn rootRtn = (RootReturn) rtn;
        Queryable persister = (Queryable) factory.getEntityPersister(rootRtn.getEntityName());
        entityPersisters.add(persister);
        lockModes.add((rootRtn.getLockMode()));
        resultColumnProcessors.add(new NonScalarResultColumnProcessor(returnableCounter++));
        nonScalarReturnList.add(rtn);
        entityOwners.add(-1);
        resultTypes.add(persister.getType());
        specifiedAliases.add(rootRtn.getAlias());
        entityAliases.add(rootRtn.getEntityAliases());
        ArrayHelper.addAll(querySpaces, persister.getQuerySpaces());
        includeInResultRowList.add(true);
      } else if (rtn instanceof CollectionReturn) {
        CollectionReturn collRtn = (CollectionReturn) rtn;
        String role = collRtn.getOwnerEntityName() + "." + collRtn.getOwnerProperty();
        QueryableCollection persister = (QueryableCollection) factory.getCollectionPersister(role);
        collectionPersisters.add(persister);
        lockModes.add(collRtn.getLockMode());
        resultColumnProcessors.add(new NonScalarResultColumnProcessor(returnableCounter++));
        nonScalarReturnList.add(rtn);
        collectionOwners.add(-1);
        resultTypes.add(persister.getType());
        specifiedAliases.add(collRtn.getAlias());
        collectionAliases.add(collRtn.getCollectionAliases());
        // determine if the collection elements are entities...
        Type elementType = persister.getElementType();
        if (elementType.isEntityType()) {
          Queryable elementPersister =
              (Queryable) ((EntityType) elementType).getAssociatedJoinable(factory);
          entityPersisters.add(elementPersister);
          entityOwners.add(-1);
          entityAliases.add(collRtn.getElementEntityAliases());
          ArrayHelper.addAll(querySpaces, elementPersister.getQuerySpaces());
        }
        includeInResultRowList.add(true);
      } else if (rtn instanceof EntityFetchReturn) {
        EntityFetchReturn fetchRtn = (EntityFetchReturn) rtn;
        NonScalarReturn ownerDescriptor = fetchRtn.getOwner();
        int ownerIndex = nonScalarReturnList.indexOf(ownerDescriptor);
        entityOwners.add(ownerIndex);
        lockModes.add(fetchRtn.getLockMode());
        Queryable ownerPersister = determineAppropriateOwnerPersister(ownerDescriptor);
        EntityType fetchedType =
            (EntityType) ownerPersister.getPropertyType(fetchRtn.getOwnerProperty());
        String entityName = fetchedType.getAssociatedEntityName(getFactory());
        Queryable persister = (Queryable) factory.getEntityPersister(entityName);
        entityPersisters.add(persister);
        nonScalarReturnList.add(rtn);
        specifiedAliases.add(fetchRtn.getAlias());
        entityAliases.add(fetchRtn.getEntityAliases());
        ArrayHelper.addAll(querySpaces, persister.getQuerySpaces());
        includeInResultRowList.add(false);
      } else if (rtn instanceof CollectionFetchReturn) {
        CollectionFetchReturn fetchRtn = (CollectionFetchReturn) rtn;
        NonScalarReturn ownerDescriptor = fetchRtn.getOwner();
        int ownerIndex = nonScalarReturnList.indexOf(ownerDescriptor);
        collectionOwners.add(ownerIndex);
        lockModes.add(fetchRtn.getLockMode());
        Queryable ownerPersister = determineAppropriateOwnerPersister(ownerDescriptor);
        String role = ownerPersister.getEntityName() + '.' + fetchRtn.getOwnerProperty();
        QueryableCollection persister = (QueryableCollection) factory.getCollectionPersister(role);
        collectionPersisters.add(persister);
        nonScalarReturnList.add(rtn);
        specifiedAliases.add(fetchRtn.getAlias());
        collectionAliases.add(fetchRtn.getCollectionAliases());
        // determine if the collection elements are entities...
        Type elementType = persister.getElementType();
        if (elementType.isEntityType()) {
          Queryable elementPersister =
              (Queryable) ((EntityType) elementType).getAssociatedJoinable(factory);
          entityPersisters.add(elementPersister);
          entityOwners.add(ownerIndex);
          entityAliases.add(fetchRtn.getElementEntityAliases());
          ArrayHelper.addAll(querySpaces, elementPersister.getQuerySpaces());
        }
        includeInResultRowList.add(false);
      } else {
        throw new HibernateException(
            "unexpected custom query return type : " + rtn.getClass().getName());
      }
    }

    this.entityPersisters = new Queryable[entityPersisters.size()];
    for (int i = 0; i < entityPersisters.size(); i++) {
      this.entityPersisters[i] = (Queryable) entityPersisters.get(i);
    }
    this.entiytOwners = ArrayHelper.toIntArray(entityOwners);
    this.entityAliases = new EntityAliases[entityAliases.size()];
    for (int i = 0; i < entityAliases.size(); i++) {
      this.entityAliases[i] = (EntityAliases) entityAliases.get(i);
    }

    this.collectionPersisters = new QueryableCollection[collectionPersisters.size()];
    for (int i = 0; i < collectionPersisters.size(); i++) {
      this.collectionPersisters[i] = (QueryableCollection) collectionPersisters.get(i);
    }
    this.collectionOwners = ArrayHelper.toIntArray(collectionOwners);
    this.collectionAliases = new CollectionAliases[collectionAliases.size()];
    for (int i = 0; i < collectionAliases.size(); i++) {
      this.collectionAliases[i] = (CollectionAliases) collectionAliases.get(i);
    }

    this.lockModes = new LockMode[lockModes.size()];
    for (int i = 0; i < lockModes.size(); i++) {
      this.lockModes[i] = (LockMode) lockModes.get(i);
    }

    this.resultTypes = ArrayHelper.toTypeArray(resultTypes);
    this.transformerAliases = ArrayHelper.toStringArray(specifiedAliases);

    this.rowProcessor =
        new ResultRowProcessor(
            hasScalars,
            (ResultColumnProcessor[])
                resultColumnProcessors.toArray(
                    new ResultColumnProcessor[resultColumnProcessors.size()]));

    this.includeInResultRow = ArrayHelper.toBooleanArray(includeInResultRowList);
  }
 @Override
 public String getName() {
   return "component" + ArrayHelper.toString(propertyNames);
 }
  private void renderSQL() throws QueryException, MappingException {

    final int rtsize;
    if (returnedTypes.size() == 0 && scalarTypes.size() == 0) {
      // ie no select clause in HQL
      returnedTypes = fromTypes;
      rtsize = returnedTypes.size();
    } else {
      rtsize = returnedTypes.size();
      Iterator iter = entitiesToFetch.iterator();
      while (iter.hasNext()) {
        returnedTypes.add(iter.next());
      }
    }
    int size = returnedTypes.size();
    persisters = new Queryable[size];
    names = new String[size];
    owners = new int[size];
    ownerAssociationTypes = new EntityType[size];
    suffixes = new String[size];
    includeInSelect = new boolean[size];
    for (int i = 0; i < size; i++) {
      String name = (String) returnedTypes.get(i);
      // if ( !isName(name) ) throw new QueryException("unknown type: " + name);
      persisters[i] = getEntityPersisterForName(name);
      // TODO: cannot use generateSuffixes() - it handles the initial suffix differently.
      suffixes[i] = (size == 1) ? "" : Integer.toString(i) + '_';
      names[i] = name;
      includeInSelect[i] = !entitiesToFetch.contains(name);
      if (includeInSelect[i]) selectLength++;
      if (name.equals(collectionOwnerName)) collectionOwnerColumn = i;
      String oneToOneOwner = (String) oneToOneOwnerNames.get(name);
      owners[i] = (oneToOneOwner == null) ? -1 : returnedTypes.indexOf(oneToOneOwner);
      ownerAssociationTypes[i] = (EntityType) uniqueKeyOwnerReferences.get(name);
    }

    if (ArrayHelper.isAllNegative(owners)) owners = null;

    String scalarSelect = renderScalarSelect(); // Must be done here because of side-effect! yuck...

    int scalarSize = scalarTypes.size();
    hasScalars = scalarTypes.size() != rtsize;

    returnTypes = new Type[scalarSize];
    for (int i = 0; i < scalarSize; i++) {
      returnTypes[i] = (Type) scalarTypes.get(i);
    }

    QuerySelect sql = new QuerySelect(getFactory().getDialect());
    sql.setDistinct(distinct);

    if (!shallowQuery) {
      renderIdentifierSelect(sql);
      renderPropertiesSelect(sql);
    }

    if (collectionPersister != null) {
      sql.addSelectFragmentString(collectionPersister.selectFragment(fetchName, "__"));
    }

    if (hasScalars || shallowQuery) sql.addSelectFragmentString(scalarSelect);

    // TODO: for some dialects it would be appropriate to add the renderOrderByPropertiesSelect() to
    // other select strings
    mergeJoins(sql.getJoinFragment());

    sql.setWhereTokens(whereTokens.iterator());

    sql.setGroupByTokens(groupByTokens.iterator());
    sql.setHavingTokens(havingTokens.iterator());
    sql.setOrderByTokens(orderByTokens.iterator());

    if (collectionPersister != null && collectionPersister.hasOrdering()) {
      sql.addOrderBy(collectionPersister.getSQLOrderByString(fetchName));
    }

    scalarColumnNames = NameGenerator.generateColumnNames(returnTypes, getFactory());

    // initialize the Set of queried identifier spaces (ie. tables)
    Iterator iter = collections.values().iterator();
    while (iter.hasNext()) {
      CollectionPersister p = getCollectionPersister((String) iter.next());
      addQuerySpaces(p.getCollectionSpaces());
    }
    iter = typeMap.keySet().iterator();
    while (iter.hasNext()) {
      Queryable p = getEntityPersisterForName((String) iter.next());
      addQuerySpaces(p.getQuerySpaces());
    }

    sqlString = sql.toQueryString();

    if (holderClass != null)
      holderConstructor = ReflectHelper.getConstructor(holderClass, returnTypes);

    if (hasScalars) {
      actualReturnTypes = returnTypes;
    } else {
      actualReturnTypes = new Type[selectLength];
      int j = 0;
      for (int i = 0; i < persisters.length; i++) {
        if (includeInSelect[i]) {
          actualReturnTypes[j++] =
              getFactory()
                  .getTypeResolver()
                  .getTypeFactory()
                  .manyToOne(persisters[i].getEntityName(), shallowQuery);
        }
      }
    }
  }