Accessing the results of a simple query

You use queries to fetch information from a database, and then work with the results. You embed SQL queries in your application code so you can bind application data to the SQL queries and submit them programmatically to the PolicyCenter relational database. Result sets that relational databases return provide a programmatic cursor to let you access each result row sequentially.

You use the query builder APIs to embed queries naturally in your Gosu application code. You bind application data to your queries and submit the queries programmatically with standard Gosu syntax. PolicyCenter application databases return select objects that implement the java.lang.iterable<T> interface to let you access each entity instance in the result sequentially.

For example, the following Gosu code creates a query of the Address entity instances in the application database. The query binds the constant "Chicago" to the compare predicate on the property City, which restricts the results.

uses gw.api.database.Query
uses gw.api.database.QuerySelectColumns
uses gw.api.path.Paths

// Specify what you want to select.
var query = Query.make(Address)
query.compare(Address#City, Equals, "Chicago")

// Specify how you want the result returned.
var select = query.select()
select.orderBy(QuerySelectColumns.path(Paths.make(Address#PostalCode)))

// Fetch the data with a for loop and print it.
for (address in select) {
  print (address.AddressLine1 + ", " + address.City + ", " + address.PostalCode)
}

When the preceding code begins the for loop, the application database fetches Address instances in the city of Chicago and sorts them by postal code. The for loop passes addresses in the result one at a time to the statements inside the for block. The for block prints each address on a separate line.

Alternatively, the following Gosu code uses an iterator and a while loop to fetch matching Address instances in the order specified.

uses gw.api.database.Query 
uses gw.api.database.QuerySelectColumns
uses gw.api.path.Paths

// Specify what you want to select.
var query = Query.make(Address)
query.compare(Address#City, Equals, "Chicago")

// Specify how you want the result returned.
var select = query.select()
select.orderBy(QuerySelectColumns.path(Paths.make(Address#PostalCode)))

// Fetch the data with a while loop and print it.
var result = select.iterator()
while (result.hasNext()) {
  var address = result.next()
  print (address.AddressLine1 + ", " + address.City + ", " + address.PostalCode)
}

There are no consequential functional or performance differences between iterating results with a for loop and iterating results with an iterator.