【问题标题】:Is there a way to query by example in Jooq?有没有办法在 Jooq 中通过示例进行查询?
【发布时间】:2016-02-13 12:37:16
【问题描述】:

我有一个由 Jooq 生成的 PersonPojoPersonRecord

现在我想做这样的事情:

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

当前版本(3.7)可以吗?

【问题讨论】:

    标签: java sql jooq


    【解决方案1】:

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

    【讨论】:

    • 这不是我真正想要的。我在 jooq 中想要这样的东西:stackoverflow.com/a/2883478/5553845。所以您可以创建任何 Person 对象 - 将其用作过滤器并创建 SQL 并运行它。
    • @UserX:好的,我不知道 QBE 是一个正式的概念。有趣的。在 jOOQ 中原生地添加对它的支持会很好。我已经更新了答案。
    • 这就是我所期待的。感谢您的回答。我试图构建类似的东西 - 但不知道 DSL.trueCondition(); 方法。
    猜你喜欢
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2019-03-04
    • 1970-01-01
    相关资源
    最近更新 更多