If the named query has the "query" hint, it uses the hint value (which must be jpa QL) to create a new query and append to it the proper order by clause.
540996
private String getQueryString(Query query) {
        Map<String, Object> hints = query.getHints();
        return hints != null ? (String) hints.get("query") : null;
    }
644801
private static void addOrder(PersistentEntity entity,
                                 CriteriaQuery query,
                                 From queryRoot,
                                 CriteriaBuilder criteriaBuilder,
                                 String sort, String order, boolean ignoreCase) {
        if (sort.equalsIgnoreCase(entity.getIdentity().getName())) {
            Expression path = queryRoot;

            if (ignoreCase) {
                path = criteriaBuilder.upper(path);
            }
            if (DynamicFinder.ORDER_DESC.equals(order)) {
                query.orderBy(criteriaBuilder.desc(path));
            } else {
                query.orderBy(criteriaBuilder.asc(path));
            }
        } else {
            Expression path = queryRoot.get(sort);

            if (ignoreCase) {
                path = criteriaBuilder.upper(path);
            }
            if (DynamicFinder.ORDER_DESC.equals(order)) {
                query.orderBy(criteriaBuilder.desc(path));
            } else {
                query.orderBy(criteriaBuilder.asc(path));
            }
        }
    }
733392
def _query_helper(self, by=None):
        
        if by is None:
            primary_keys = self.table.primary_key.columns.keys()

            if len(primary_keys) > 1:
                warnings.warn("WARNING: MORE THAN 1 PRIMARY KEY FOR TABLE %s. "
                              "USING THE FIRST KEY %s." %
                              (self.table.name, primary_keys[0]))

            if not primary_keys:
                raise NoPrimaryKeyException("Table %s needs a primary key for"
                                            "the .last() method to work properly. "
                                            "Alternatively, specify an ORDER BY "
                                            "column with the by= argument. " %
                                            self.table.name)
            id_col = primary_keys[0]
        else:
            id_col = by

        if self.column is None:
            col = "*"
        else:
            col = self.column.name

        return col, id_col
598507
public EbeanQueryWrapper bindAndPrepare(EbeanQueryWrapper query) {
        Assert.notNull(query, "query must not be null!");
        return bindAndPrepare(query, parameters);
    }
874037
private void addAction(NamedParameterStatement nps, Map<String, String> keysToColumns, Map<String, Object>[] maps) throws SQLException {
		Map<String, Object> params = new HashMap<>();

		for (Map.Entry<String, String> entry : keysToColumns.entrySet()) {
			for (Map<String, Object> map : maps) {
				if (map.containsKey(entry.getKey())) {
					params.put(entry.getValue(), map.get(entry.getKey()));
					break;
				}
			}
		}

		if (params.size() < keysToColumns.size()) {
			Set<String> requiredParams = keysToColumns.keySet();
			requiredParams.removeAll(params.keySet());
			throw new RuntimeException(String.format("Insufficient params: not sent params for query= %s", requiredParams));
		}

		nps.setParameters(params);
		nps.addBatch();
	}
442513
private QueryImpl makeQuery(Session session) throws InvalidQueryException, RepositoryException
   {
      StatementContext context = new StatementContext();
      context.statement = new StringBuilder("SELECT * FROM ");
      context.statement.append(JCROrganizationServiceImpl.JOS_USERS_NODETYPE);

      if (query.getUserName() != null)
      {
         addStringStatement(context, UserProperties.JOS_USER_NAME, query.getUserName());
      }

      if (query.getFirstName() != null)
      {
         addStringStatement(context, UserProperties.JOS_FIRST_NAME, query.getFirstName());
      }

      if (query.getLastName() != null)
      {
         addStringStatement(context, UserProperties.JOS_LAST_NAME, query.getLastName());
      }

      if (query.getEmail() != null)
      {
         addStringStatement(context, UserProperties.JOS_EMAIL, query.getEmail());
      }

      if (query.getFromLoginDate() != null)
      {
         addDateStatement(context, UserProperties.JOS_LAST_LOGIN_TIME, ">=", query.getFromLoginDate());
      }

      if (query.getToLoginDate() != null)
      {
         addDateStatement(context, UserProperties.JOS_LAST_LOGIN_TIME, "<=", query.getToLoginDate());
      }

      if (status != UserStatus.ANY)
      {
         context.statement.append(" AND ").append(JCROrganizationServiceImpl.JOS_DISABLED);
         if (status == UserStatus.ENABLED)
            context.statement.append(" IS NULL");
         else
            context.statement.append(" IS NOT NULL");
      }

      return (QueryImpl)session.getWorkspace().getQueryManager().createQuery(context.statement.toString(), Query.SQL);
   }
1135797
void appendSql(String tableName, StringBuilder sb, List<ArgumentHolder> columnArgList) throws SQLException {
		if (clauseStackLevel == 0) {
			throw new IllegalStateException("No where clauses defined.  Did you miss a where operation?");
		}
		if (clauseStackLevel != 1) {
			throw new IllegalStateException(
					"Both the \"left-hand\" and \"right-hand\" clauses have been defined.  Did you miss an AND or OR?");
		}
		if (needsFuture != null) {
			throw new IllegalStateException(
					"The SQL statement has not been finished since there are previous operations still waiting for clauses.");
		}

		// we don't pop here because we may want to run the query multiple times
		peek().appendSql(databaseType, tableName, sb, columnArgList);
	}
784635
private Optional<ConcreteProposal> propose(InnerJoinNode joinNode, ImmutableMultimap<RelationPredicate, ExtensionalDataNode> initialDataNodeMap,
                                               ImmutableList<Variable> priorityVariables,
                                               IntermediateQuery query, DBMetadata dbMetadata)
            throws AtomUnificationException {

        ImmutableList.Builder<PredicateLevelProposal> proposalListBuilder = ImmutableList.builder();

        for (RelationPredicate predicate : initialDataNodeMap.keySet()) {
            ImmutableCollection<ExtensionalDataNode> initialNodes = initialDataNodeMap.get(predicate);
            Optional<PredicateLevelProposal> predicateProposal = proposePerPredicate(joinNode, initialNodes, predicate, dbMetadata,
                    priorityVariables, query);
            predicateProposal.ifPresent(proposalListBuilder::add);
        }

        return createConcreteProposal(proposalListBuilder.build(), priorityVariables);
    }
1281463
private String buildSelectSQL(boolean addOrderBy) {
        SQLParams sqlParams = SQLParams.builder()
                .modelClass(this.modelClass)
                .selectColumns(this.selectColumns)
                .tableName(this.tableName)
                .pkName(this.primaryKeyColumn)
                .conditionSQL(this.conditionSQL)
                .excludedColumns(this.excludedColumns)
                .isSQLLimit(isSQLLimit)
                .build();

        ifThen(addOrderBy, () -> sqlParams.setOrderBy(this.orderBySQL.toString()));

        return Anima.of().dialect().select(sqlParams);
    }
884171
public @NotNull QueryBuilder append(@SuppressWarnings("ParameterHidesMemberVariable") @NotNull SqlQuery query) {
        this.query.append(query.getSql());
        arguments.addAll(query.getArguments());
        return this;
    }
1149972
public void addParamQuery(String name, String value) {
        addParam(name, value, NameValuePair.TYPE_QUERY_STRING);
    }
141357
function mergeQueries(query, options) {
  if (options == null) {
    return query;
  }

  Object.keys(options).forEach(key => {
    let label = key;
    let value = options[key];

    validateProp(key, value);

    switch (key) {
    case 'orderByKey':
      label = orderedBy;
      value = orderByKey;
      break;

    case 'orderByPriority':
      label = orderedBy;
      value = orderByPriority;
      break;

    case 'orderByValue':
      label = orderedBy;
      value = orderByValue;
      break;

    case 'orderByChild':
      label = orderedBy;
      break;

    default:
      break;
    }

    query[label] = value;
  });

  return query;
}
867441
private PreparedStatement prepareQuery(String tableName, Query query) {
        // All queries start with SELECT * FROM <keyspace>.<table>
        StringBuilder cql = new StringBuilder("SELECT * FROM ");
        cql.append(m_keyspace);
        cql.append(".");
        cql.append(tableName);
        
        switch (query) {
        case SELECT_1_ROW_1_COLUMN:
            cql.append(" WHERE key = ? AND column1 = ?;");
            break;
        case SELECT_1_ROW_COLUMN_RANGE:
            cql.append(" WHERE key = ? AND column1 >= ? AND column1 < ? LIMIT ?;");
            break;
        case SELECT_1_ROW_COLUMN_SET:
            cql.append(" WHERE key = ? AND column1 IN ?;");
            break;
        case SELECT_1_ROW_ALL_COLUMNS:
            cql.append(" WHERE key = ? LIMIT ?;");
            break;
        case SELECT_1_ROW_UPPER_COLUMNS:
            cql.append(" WHERE key = ? AND column1 >= ? LIMIT ?;");
            break;
        case SELECT_1_ROW_LOWER_COLUMNS:
            cql.append(" WHERE key = ? AND column1 <= ? LIMIT ?;");
            break;
        case SELECT_ROWS_RANGE:
            //unfortunately I didn't find how to get first column of each row in CQL.
            cql.append(" ;");
            break;
        default: 
            throw new RuntimeException("Not supported: " + query);
        }
        m_logger.debug("Preparing query {}: {}", query, cql);
        return ((CQLService)DBService.instance(m_tenant)).getSession().prepare(cql.toString());
    }
209698
private void setKunderaQueryTypeObject() {

        try {
            if (isSelectStatement()) {

                this.setSelectStatement((SelectStatement) (this.getJpqlExpression().getQueryStatement()));

            } else if (isUpdateStatement()) {

                this.setUpdateStatement((UpdateStatement) (this.getJpqlExpression().getQueryStatement()));

            } else if (isDeleteStatement()) {
                this.setDeleteStatement((DeleteStatement) (this.getJpqlExpression().getQueryStatement()));

            }
        } catch (ClassCastException cce) {
            throw new JPQLParseException("Bad query format : " + cce.getMessage());
        }

    }
887497
public Query<S> query(Filter<S> filter, OrderingList<S> ordering, QueryHints hints)
        throws FetchException
    {
        filter = filter.bind();

        Map<OrderingList<S>, Query<S>> map;
        synchronized (mFilterToQuery) {
            map = mFilterToQuery.get(filter);
            if (map == null) {
                if (filter == null) {
                    throw new IllegalArgumentException("Query filter must not be null");
                }
                map = new SoftValuedHashMap(7);
                mFilterToQuery.put(filter, map);
            }
        }

        Query<S> query;
        synchronized (map) {
            query = map.get(ordering);
            if (query == null) {
                FilterValues<S> values = filter.initialFilterValues();
                if (values == null && filter.isClosed()) {
                    query = new EmptyQuery<S>(this, ordering);
                } else {
                    StandardQuery<S> standardQuery = createQuery(filter, values, ordering, hints);
                    if (!mLazySetExecutor) {
                        try {
                            standardQuery.setExecutor();
                        } catch (RepositoryException e) {
                            throw e.toFetchException();
                        }
                    }
                    query = standardQuery;
                }
                map.put(ordering, query);
            }
        }

        return query;
    }
306697
private void doInterceptBeforeQuery(Class<?> clazz, StringBuilder sql, List<Object> args) {
        for (DBHelperInterceptor interceptor : interceptors) {
            boolean isContinue = interceptor.beforeSelect(clazz, sql.toString(), args);
            if (!isContinue) {
                throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
            }
        }
    }
1058514
private void addEntityGraphToFindMethodQueryHints(
      EntityGraphBean entityGraphCandidate, MethodInvocation invocation) {
    LOG.trace("Trying to push the EntityGraph candidate to the query hints find method");

    Map<String, Object> queryProperties = null;
    int index = 0;
    for (Object argument : invocation.getArguments()) {
      if (argument instanceof Map) {
        queryProperties = (Map) argument;
        break;
      }
      index++;
    }
    if (queryProperties == null) {
      LOG.trace("No query hints passed to the find method.");
      return;
    }
    if (!entityGraphCandidate.isPrimary() && QueryHintsUtils.containsEntityGraph(queryProperties)) {
      LOG.trace(
          "The query hints passed with the find method already hold an entity graph. Overriding aborted because the candidate EntityGraph is optional.");
      return;
    }

    queryProperties = new HashMap<String, Object>(queryProperties);
    QueryHintsUtils.removeEntityGraphs(queryProperties);
    queryProperties.putAll(
        QueryHintsUtils.buildQueryHints(
            (EntityManager) invocation.getThis(), entityGraphCandidate));
    invocation.getArguments()[index] = queryProperties;
  }