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:
dsl.select()
.from(BOOK)
.where(BOOK.ID.equal(5))
.and(BOOK.TITLE.equal("Animal Farm"))
.fetch();
is equivalent to the full form:
dsl.select()
.from(BOOK)
.where(BOOK.ID.equal(val(5)))
.and(BOOK.TITLE.equal(val("Animal Farm")))
.fetch();
and is converted into the SQL query:
SELECT *
FROM BOOK
WHERE BOOK.ID = ?
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.
Select<?> select =
dsl.select()
.from(BOOK)
.where(BOOK.ID.equal(5))
.and(BOOK.TITLE.equal("Animal Farm"));
Param<?> param = select.getParam("2");
Param.setValue("Animals as Leaders");
Another way to assign a new value to a parameter is to call the bind
method:
Query query1 =
dsl.select()
.from(AUTHOR)
.where(LAST_NAME.equal("Poe"));
query1.bind(1, "Orwell");
jOOQ supports named parameters, too. They need to be created explicitly using org.jooq.Param
:
// Create a query with a named parameter. You can then use that name for
// accessing the parameter again
Query query1 =
dsl.select()
.from(AUTHOR)
.where(LAST_NAME.equal(param("lastName", "Poe")));
Param<?> param1 = query.getParam("lastName");
// Or, keep a reference to the typed parameter in order
// not to lose the <T> type information:
Param<String> param2 = param("lastName", "Poe");
Query query2 =
dsl.select()
.from(AUTHOR)
.where(LAST_NAME.equal(param2));
// You can now change the bind value directly on the Param reference:
param2.setValue("Orwell");
Another way to assign a new value to a parameter is to call the bind method:
// Or, with named parameters
Query query2 =
dsl.select()
.from(AUTHOR)
.where(LAST_NAME.equal(param("lastName", "Poe")));
query2.bind("lastName", "Orwell");