UserX UserX - 5 months ago 25
SQL Question

Is there a way to query by example in Jooq?

I've a

PersonPojo
and
PersonRecord
generated by Jooq.

Now I'd like to to something like this:

Person p = new PersonPojo()
p.setId(10);
create.selectFrom(Tables.PERSON).whereLike(p).fetch();


Is it possible with the current version (3.7)?

Answer

jOOQ 3.8+ solution

Query By Example (QBE) support was implemented in jOOQ 3.8 with #4735. You can write:

Person p = new PersonPojo();
p.setId(10);

PersonRecord record = new PersonRecord();
record.from(p); // Reuse pre-existing reflection functionality here.

create.selectFrom(Tables.PERSON).where(DSL.condition(record)).fetch();

For more details, please refer to the Javadoc:

jOOQ 3.7 or less solution

In older jOOQ versions, you can implement QBE yourself:

Person p = new PersonPojo();
p.setId(10);

PersonRecord record = new PersonRecord();
record.from(p); // Reuse pre-existing reflection functionality here.

Condition condition = DSL.trueCondition();
for (Field<?> field : record.fields())
    if (record.getValue(field) != null)
        condition = condition.and(((Field) field).eq(record.getValue(field)));

create.selectFrom(Tables.PERSON).where(condition).fetch();

Or, using Java 8:

create.selectFrom(Tables.PERSON)
      .where(Stream.of(record.fields())
                   .filter(f -> record.getValue(f) != null)
                   .reduce(
                        DSL.trueCondition(),
                        (c, f) -> c.and(((Field) f).eq(record.getValue(f))),
                        (c1, c2) -> c1.and(c2)
                   ))
      .fetch();