Java 8 ha raggiunto la fine del supporto
e verrà
ritirato
il 31 gennaio 2026. Dopo il ritiro, non potrai eseguire il deployment di applicazioni Java 8, anche se la tua organizzazione ha utilizzato in precedenza un criterio dell'organizzazione per riattivare i deployment di runtime legacy. Le tue applicazioni Java 8 esistenti continueranno a essere eseguite e a ricevere traffico dopo la
data di ritiro. Ti consigliamo di
eseguire la migrazione all'ultima versione supportata di Java.
Recupero dei risultati delle query
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Dopo aver creato una query, puoi specificare una serie di opzioni di recupero per
controllare ulteriormente i risultati restituiti.
Per ulteriori informazioni sulla strutturazione delle query per la tua app, consulta la sezione Query Datastore.
Recupero di una singola entità
Per recuperare una sola entità corrispondente alla query, utilizza il metodo PreparedQuery.asSingleEntity()
:
Restituisce il primo risultato trovato nell'indice che corrisponde alla query.
Se è presente più di un risultato corrispondente, viene generato un TooManyResultsException
.
Iterazione tra i risultati delle query
Quando esegui l'iterazione dei risultati di una query utilizzando i metodi PreparedQuery.asIterable()
e PreparedQuery.asIterator()
, Cloud Datastore recupera i risultati in batch. Per impostazione predefinita, ogni batch contiene 20 risultati, ma puoi modificare questo valore utilizzando FetchOptions.chunkSize()
. Puoi continuare a scorrere i risultati della query finché non vengono restituiti tutti o la richiesta non scade.
Recupero delle proprietà selezionate da un'entità
Per recuperare solo le proprietà selezionate di un'entità anziché l'intera entità, utilizza una query di proiezione. Questo tipo di query viene eseguito più rapidamente e costa meno di una che restituisce entità complete.
Allo stesso modo, una query basata solo su chiavi consente di risparmiare tempo e risorse restituendo solo le chiavi delle entità corrispondenti, anziché le entità complete. Per creare questo tipo di query, utilizza il metodo Query.setKeysOnly()
:
Impostare un limite per la query
Puoi specificare un limite per la query per controllare il numero massimo di risultati restituiti in un batch. L'esempio seguente recupera le cinque persone più alte da Cloud Datastore:
Passaggi successivi
Salvo quando diversamente specificato, i contenuti di questa pagina sono concessi in base alla licenza Creative Commons Attribution 4.0, mentre gli esempi di codice sono concessi in base alla licenza Apache 2.0. Per ulteriori dettagli, consulta le norme del sito di Google Developers. Java è un marchio registrato di Oracle e/o delle sue consociate.
Ultimo aggiornamento 2025-09-04 UTC.
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 2025-09-04 UTC."],[[["\u003cp\u003eThis API supports first-generation runtimes and is applicable when upgrading to corresponding second-generation runtimes, while migration to Java 11/17 runtimes requires referring to a specific migration guide.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003ePreparedQuery.asSingleEntity()\u003c/code\u003e retrieves a single entity matching a query, throwing a \u003ccode\u003eTooManyResultsException\u003c/code\u003e if multiple matches exist.\u003c/p\u003e\n"],["\u003cp\u003e\u003ccode\u003ePreparedQuery.asIterable()\u003c/code\u003e and \u003ccode\u003ePreparedQuery.asIterator()\u003c/code\u003e allow iterating through query results in batches, with the batch size adjustable via \u003ccode\u003eFetchOptions.chunkSize()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eProjection queries retrieve only selected properties, and keys-only queries retrieve only keys, both being faster and less resource-intensive than full-entity queries.\u003c/p\u003e\n"],["\u003cp\u003eA limit can be set on queries to control the maximum number of results, as demonstrated in the example that retrieves the five tallest people.\u003c/p\u003e\n"]]],[],null,["# Retrieving query results\n\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| java-gen2\n|\n| /services/access). If you are updating to the App Engine Java 11/17 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/java-differences) to learn about your migration options for legacy bundled services.\n\nAfter constructing a query, you can specify a number of retrieval options to\nfurther control the results it returns.\nSee [datastore queries](/appengine/docs/legacy/standard/java/datastore/queries) for more information on structuring queries for your app.\n\nRetrieving a single entity\n--------------------------\n\n\u003cbr /\u003e\n\nTo retrieve just a single entity matching your query, use the method [`PreparedQuery.asSingleEntity()`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/PreparedQuery#asSingleEntity--): \n\n Query q =\n new Query(\"Person\")\n .setFilter(new FilterPredicate(\"lastName\", FilterOperator.EQUAL, targetLastName));\n\n PreparedQuery pq = datastore.prepare(q);\n Entity result = pq.asSingleEntity();\n\nThis returns the first result found in the index that matches the query.\n\n(If there is more than one matching result, it throws a [`TooManyResultsException`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/PreparedQuery.TooManyResultsException).)\n\n\nIterating through query results\n-------------------------------\n\nWhen iterating through the results of a query using the [`PreparedQuery.asIterable()`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/PreparedQuery#asIterable()) and [`PreparedQuery.asIterator()`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/PreparedQuery#asiterator_1) methods, Cloud Datastore retrieves the results in batches. By default each batch contains 20 results, but you can change this value using [`FetchOptions.chunkSize()`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/FetchOptions#chunksize). You can continue iterating through query results until all are returned or the request times out.\n\nRetrieving selected properties from an entity\n---------------------------------------------\n\nTo retrieve only selected properties of an entity rather than the entire entity, use a [*projection query*](/appengine/docs/legacy/standard/java/datastore/projectionqueries). This type of query runs faster and costs less than one that returns complete entities.\n\nSimilarly, a [*keys-only query*](/appengine/docs/legacy/standard/java/datastore/queries#keys-only_queries) saves time and resources by returning just the keys to the entities it matches, rather than the full entities themselves. To create this type of query, use the [`Query.setKeysOnly()`](/appengine/docs/legacy/standard/java/javadoc/com/google/appengine/api/datastore/Query#setkeysonly) method: \n\n Query q = new Query(\"Person\").setKeysOnly();\n\nSetting a limit for your query\n------------------------------\n\nYou can specify a *limit* for your query to control the maximum number of results returned in one batch. The following example retrieves the five tallest people from Cloud Datastore: \n\n private List\u003cEntity\u003e getTallestPeople() {\n DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();\n\n Query q = new Query(\"Person\").addSort(\"height\", SortDirection.DESCENDING);\n\n PreparedQuery pq = datastore.prepare(q);\n return pq.asList(FetchOptions.Builder.withLimit(5));\n }\n\nWhat's next?\n------------\n\n- Learn the [common restrictions](/appengine/docs/legacy/standard/java/datastore/query-restrictions) for queries on Cloud Datastore.\n- Learn about [query cursors](/appengine/docs/legacy/standard/java/datastore/query-cursors), which allow an application to retrieve a query's results in convenient batches.\n- [Understand data consistency](/appengine/docs/legacy/standard/java/datastore/data-consistency) and how data consistency works with different types of queries on Cloud Datastore.\n- Learn the [basic syntax and structure of queries](/appengine/docs/legacy/standard/java/datastore/queries) for Cloud Datastore."]]