Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
DataContext dc = ...
Table table = dc.getDefaultSchema().getTableByName("person");
Column col1 = table.getColumnByName("id");
Column col2 = table.getColumnByName("name");
Column col3 = table.getColumnByName("age");
 
// Construct a query like "SELECT id, name FROM person WHERE age > 18"
Query q = new Query();
q.from(table);
q.select(col1, col2);
q.where(col3, OperatorType.GREATER_THAN, 18);
 
// Execute the Query
DataSet ds = dc.executeQuery(q);

...

  • Creating the query this way is a bit verbose, and as we shall see below, it can be made simpler in most cases.

2 - The Query-builder API

To make query definition easier and more developer-guided, Apache MetaModel also has the so-called Query-builder API

...

. This term is used for the set of methods extending from a call to DataContext.query(), ending with either .toQuery() or .execute(). Using the same simple example as before, we can define and execute the query like this:

 

Code Block
languagejava
DataContext dc = ...
DataSet ds = dc.query().from("person").select("id", "name").where("age").gt(18).execute();

 

Pros:

  • The API is easier to read than using the Query class directly.
  • The API helps select which methods are meaningful in the given context, eliminating choices to what makes sense.
  • The API does not require you to hold a Query object if you wish to immediately just execute it.

Cons:

  • Some features are not available via this API, for instance sub-querying.

3 - Query parsing

Finally, Apache MetaModel allows you to simply parse a query from a string form. You can use this feature in a two-step parse-then-execute mode or in a single step to parse-and-execute.

...