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.Nametype which models identifiers. It can be constructed withDSL.name(String...)from fully qualified names in String form, e.g.:You can then pass such a name to the
DSL.field(Name)constructor, e.g.:On jOOQ versions
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