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

时间:2015-11-12 08:32:57

标签: java sql jooq

我是由Jooq生成的PersonPojoPersonRecord

现在我想要这样的事情:

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

是否可以使用当前版本(3.7)?

1 个答案:

答案 0 :(得分:2)

jOOQ 3.8+解决方案

Query By Example (QBE)支持在jOOQ 3.8中使用#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();
相关问题