/*
   * INTERNAL:
   * If this query key represents a foreign reference answer the
   * base expression -> foreign reference join criteria.
   */
  public Expression mappingCriteria() {
    Expression selectionCriteria;

    // First look for a query key, then a mapping
    if (getQueryKeyOrNull() == null) {
      if ((getMapping() == null) || (!getMapping().isForeignReferenceMapping())) {
        return null;
      } else {
        // The join criteria is now twisted by the mappings.
        selectionCriteria = ((ForeignReferenceMapping) getMapping()).getJoinCriteria(this);
      }
    } else {
      if (!getQueryKeyOrNull().isForeignReferenceQueryKey()) {
        return null;
      } else {
        selectionCriteria = ((ForeignReferenceQueryKey) getQueryKeyOrNull()).getJoinCriteria();
        selectionCriteria = getBaseExpression().twist(selectionCriteria, this);
      }
    }

    if (shouldUseOuterJoin() && getSession().getPlatform().shouldPrintOuterJoinInWhereClause()) {
      selectionCriteria = selectionCriteria.convertToUseOuterJoin();
    }

    return selectionCriteria;
  }
  /**
   * INTERNAL: Return the expression to join the main table of this node to any auxiliary tables.
   */
  public Expression additionalExpressionCriteria() {
    if (getDescriptor() == null) {
      return null;
    }

    Expression criteria = getDescriptor().getQueryManager().getAdditionalJoinExpression();
    if (criteria != null) {
      criteria = getBaseExpression().twist(criteria, this);
      if (shouldUseOuterJoin() && getSession().getPlatform().shouldPrintOuterJoinInWhereClause()) {
        criteria.convertToUseOuterJoin();
      }
    }
    if (getSession().getPlatform().shouldPrintOuterJoinInWhereClause()) {
      if (isUsingOuterJoinForMultitableInheritance()) {
        Expression childrenCriteria =
            getDescriptor().getInheritancePolicy().getChildrenJoinExpression();
        childrenCriteria = getBaseExpression().twist(childrenCriteria, this);
        childrenCriteria.convertToUseOuterJoin();
        if (criteria == null) {
          criteria = childrenCriteria;
        } else {
          criteria = criteria.and(childrenCriteria);
        }
      }
    }
    if ((getDescriptor() != null) && (getDescriptor().getHistoryPolicy() != null)) {
      Expression historyCriteria =
          getDescriptor().getHistoryPolicy().additionalHistoryExpression(this);
      if (criteria != null) {
        criteria = criteria.and(historyCriteria);
      } else {
        criteria = historyCriteria;
      }
    }
    return criteria;
  }