3

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

Tunaki
  • 132,869
  • 46
  • 340
  • 423
kiru
  • 119
  • 1
  • 2
  • 9

1 Answers1

3

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();
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • That's not really what I wanted. I want something like this in jooq: http://stackoverflow.com/a/2883478/5553845 .So you can create any Person objects - use that as a filter and create a SQL and run it. – kiru Nov 12 '15 at 15:01
  • 1
    @UserX: OK, I wasn't aware of QBE as a formal concept. Interesting. Would be nice to add support for that in jOOQ, natively. I've updated the answer. – Lukas Eder Nov 12 '15 at 15:43
  • That's what I was expecting. Thanks for the answer. I tried to build something like that - but was not aware of the `DSL.trueCondition();` method. – kiru Nov 12 '15 at 16:39