Binding Variables

Dari supports bind variables in query strings using ? for placeholders.

Binding Variables of Simple Types

In a basic scenario, placeholders refer to variables with single values or single objects, such as String, Integer, or Date.

 String userName = "John Smith";
 User user = Query.from(User.class)
                 .where("name = ?", userName).first();

Referring to the previous snippet, at runtime Dari creates the following where clause:

WHERE name = 'John Smith'

In the next example, the query filters on a Date object, returning all ToolUsers for which the last login date is after January 17, 2019.

 String startDateString = "01/17/2019";
 DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
 Date date = null;

 try {
     date = df.parse(startDateString);
 }
 catch (ParseException e) {
     /* Error handling */
 }

 List<ToolUser> toolUser = Query.from(ToolUser.class)
                                 .where("lastLoginDate  >  ?", date).selectAll();

Binding Collection Variables

You can also bind a variable that is a collection, such as a Set or List, to a query. At run time, Dari performs the operation in the .where method against all elements in the collection. In the following snippet, the query searches for all instances of User with a name value that matches any name in the list names.

 List<String> names = new ArrayList<String>();
 names.add("John Smith");
 names.add("Jane Doe");
 List<User> users = Query.from(User.class)
                         .where("name = ?", names).selectAll();

Using Positional Binding

If a .where method has more than one placeholder, Dari substitutes the placeholders for the parameters in the order they appear.

List<ToolUser> toolUser = Query.from(ToolUser.class)
                               .where("name = ? OR email = ?", "worf", "worf@klingon.com")
                               .selectAll();

Referring to the previous snippet, at runtime Dari creates the following where clause:

WHERE name = 'worf' OR email = 'worf@klingon.com'

You can indicate the value for a placeholder by specifying a position—a useful technique to avoid repeating the same value in a long list of parameters.

List<Author> authors = Query.from(Author.class)
                             .where("firstName = ?0 OR lastName = ?0 OR email contains ?1", "rand", "brightspot.com").selectAll();

Referring to the previous snippet, at runtime Dari creates the following where clause:

WHERE firstName = 'rand'
OR lastName = 'rand'
OR email LIKE '%brightspot.com%'