I'm trying to use jOOQ to build SQL queries in some generic code. I'm not interested in using jOOQ to execute those queries or to examine the results. Also, this code is generic so I cannot use jOOQ's code generation.
I have managed to figure out this much:
List<org.jooq.Field<?>> fields = new ArrayList<org.jooq.Field<?>>();
Field<?> field = Factory.field("somefield");
fields.add(field);
field = Factory.field("someotherfield");
fields.add(field);
Field<Object> fieldPK = Factory.field("somePKField");
Condition condition = fieldPK.equal(123);
Factory factory = new Factory(connection, SQLDialect.POSTGRES);
SelectFinalStep step = factory.select(fields).from("sometable").where(condition);
String query = step.getQuery().getSQL(true);
But Factory.field() and from() take generic SQL rather than actual table or field names, so there's no quoting (even when using RenderNameStyle.QUOTED) and no protection against SQL injection.
Is there any way to create a Field or Table that know what their names are? Ideally, I could specify a Field by both its name and its parent table, with jOOQ building the "sometable"."somefield" string for me.
jOOQ knows the org.jooq.Name
type which models identifiers. It can be constructed with DSL.name(String...)
from fully qualified names in String form, e.g.:
Name name1 = name("column");
Name name2 = name("table", "column");
Name name3 = name("schema", "table", "column");
Name name4 = name("catalog", "schema", "table", "column");
You can then pass such a name to the DSL.field(Name)
constructor, e.g.:
Field<Object> field1 = field(name("table", "column"));
Field<String> field2 = field(name("table", "column"), String.class);
Side-note: The question was asked in the context of jOOQ 2.x, but few people are still using this old version, which is why this answer assumes using jOOQ 3.x
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With