Search code examples
javasqljooq

Define dynamically what columns to update in jOOQ


I have this jOOQ example that could either update COLUMN_A or COLUMN_B

context.update(MY_TABLE)
        .set(MY_TABLE.COLUMN_A, fieldA)
        .where(MY_TABLE.SK.eq(sk))
        .execute();


context.update(MY_TABLE)
        .set(MY_TABLE.COLUMN_B, fieldB)
        .where(MY_TABLE.SK.eq(sk))
        .execute();

I want to have a single code instead of two snippets, how to extract the .set portion into a variable to be able to do that? Something along these lines:

if (option == 1)
    setColumn = `(MY_TABLE.COLUMN_A, fieldA)`;
else
    setColumn = `(MY_TABLE.COLUMN_B, fieldB)`;


context.update(MY_TABLE)
        .set(setColumn)
        .where(MY_TABLE.SK.eq(sk))
        .execute();

Solution

  • Assuming all expressions share the same data type, do this:

    context.update(MY_TABLE)
            .set(option == 1 ? MY_TABLE.COLUMN_A : MY_TABLE.COLUMN_B,
                 option == 1 ? fieldA : fieldB)
            .where(MY_TABLE.SK.eq(sk))
            .execute();
    

    If you can't do this in a type safe way, you could use rawtype casts, or omit type safety using a Map:

    context.update(MY_TABLE)
            .set(option == 1 
               ? Map.of(MY_TABLE.COLUMN_A, fieldA) 
               : Map.of(MY_TABLE.COLUMN_B, fieldB))
            .where(MY_TABLE.SK.eq(sk))
            .execute();