Instantiating a jooq Field<> by name

两盒软妹~` 提交于 2019-12-07 01:30:55

问题


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.


回答1:


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);

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



来源:https://stackoverflow.com/questions/10264001/instantiating-a-jooq-field-by-name

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!