7.6.2. Named and Unnamed Parameters

By default, any time you present a query containing a parameter that is string literal, a date, a number literal or an external variable, jOOQ uses unnamed parameters to bind that variable or literal. To illustrate, the following expression in Java:

  1. dsl.select()
  2. .from(BOOK)
  3. .where(BOOK.ID.equal(5))
  4. .and(BOOK.TITLE.equal("Animal Farm"))
  5. .fetch();

is equivalent to the full form:

  1. dsl.select()
  2. .from(BOOK)
  3. .where(BOOK.ID.equal(val(5)))
  4. .and(BOOK.TITLE.equal(val("Animal Farm")))
  5. .fetch();

and is converted into the SQL query:

  1. SELECT *
  2. FROM BOOK
  3. WHERE BOOK.ID = ?
  4. AND BOOK.TITLE = ?

You need not concern yourself with the index position of the field value that corresponds to a parameter, as the values will be bound to the appropriate parameter automatically. The index of the parameter list is 1-based. If you need to change the value of a parameter, you just select it by its index number.

  1. Select<?> select =
  2. dsl.select()
  3. .from(BOOK)
  4. .where(BOOK.ID.equal(5))
  5. .and(BOOK.TITLE.equal("Animal Farm"));
  6. Param<?> param = select.getParam("2");
  7. Param.setValue("Animals as Leaders");

Another way to assign a new value to a parameter is to call the bind method:

  1. Query query1 =
  2. dsl.select()
  3. .from(AUTHOR)
  4. .where(LAST_NAME.equal("Poe"));
  5. query1.bind(1, "Orwell");

jOOQ supports named parameters, too. They need to be created explicitly using org.jooq.Param:

  1. // Create a query with a named parameter. You can then use that name for
  2. // accessing the parameter again
  3. Query query1 =
  4. dsl.select()
  5. .from(AUTHOR)
  6. .where(LAST_NAME.equal(param("lastName", "Poe")));
  7. Param<?> param1 = query.getParam("lastName");
  8. // Or, keep a reference to the typed parameter in order
  9. // not to lose the <T> type information:
  10. Param<String> param2 = param("lastName", "Poe");
  11. Query query2 =
  12. dsl.select()
  13. .from(AUTHOR)
  14. .where(LAST_NAME.equal(param2));
  15. // You can now change the bind value directly on the Param reference:
  16. param2.setValue("Orwell");

Another way to assign a new value to a parameter is to call the bind method:

  1. // Or, with named parameters
  2. Query query2 =
  3. dsl.select()
  4. .from(AUTHOR)
  5. .where(LAST_NAME.equal(param("lastName", "Poe")));
  6. query2.bind("lastName", "Orwell");