简体   繁体   中英

jOOQ - Reusing SelectConditionStep

I have some code like this:

var step =
    db.select(T1.C1).
        from(T1).
        where(T1.C2.eq(v1));

var result = step.
    and(T1.C3.eq(v2)).
    fetchOne();

if(result == null) 
    result = step.
        and(T1.C3.eq(v3)).
        fetchOne();

It works properly but I'm wondering if this kind of reuse is something to be avoided due to jOOQ's internals.

For historic reasons, some elements of the DSL API are mutable, which means you should not reuse any references to intermediate "step" types in your code. This is mentioned in every "step" type's Javadoc:

Referencing XYZ*Step types directly from client code

It is usually not recommended to reference any XYZ*Step types directly from client code, or assign them to local variables. When writing dynamic SQL, creating a statement's components dynamically, and passing them to the DSL API statically is usually a better choice. See the manual's section about dynamic SQL for details:https://www.jooq.org/doc/latest/manual/sql-building/dynamic-sql .

Drawbacks of referencing the XYZ*Step types directly:

  • They're operating on mutable implementations (as of jOOQ 3.x)
  • They're less composable and not easy to get right when dynamic SQL gets complex
  • They're less readable
  • They might have binary incompatible changes between minor releases

I recommend you take the functional approach to writing dynamic SQL , instead:

Select<Result1<Integer>> fetchOne(Condition condition) {
    return db.select(T1.C1)
             .from(T1)
             .where(T1.C2.eq(v1))
             .and(condition)
             .fetchOne();
}

var result = fetchOne(T1.C3.eq(v2));

if (result == null)
    result = fetchOne(T1.C3.eq(v3));

Or, do it all in SQL to prevent the extra round trip:

var result =
db.select(T1.C1)
  .from(T1)
  .where(T1.C2.eq(v1))
  .and(T1.C3.in(v2, v3))
  .orderBy(T1.C3.sortAsc(v2, v3))
  .limit(1)
  .fetchOne()

This is using the Field.sortAsc() convenience method.

See also this blog post for more insight on why not to reference the XYZStep types directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM