有没有办法在 Jooq 中通过示例查询?

Is there a way to query by example in Jooq?

我有一个由 Jooq 生成的 PersonPojoPersonRecord

现在我想做这样的事情:

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

当前版本 (3.7) 可以吗?

jOOQ 3.8+ 解决方案

Query By Example (QBE) support was implemented in jOOQ 3.8 with #4735。你可以这样写:

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

详情请参考Javadoc:

jOOQ 3.7以下解决方案

在旧的 jOOQ 版本中,您可以自己实现 QBE:

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

或者,使用 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();