Search code examples
javadatabasejooq

Insert a record with where clause using jooq


I'm streaming master data and want to be able to process only data that are intended to. Therefore I'm fetching data from another table while inserting the data. Using Jooq it currently looks like:

public boolean writeRecord(TypeA typeA) {
    Result<Record> result = context
      .insertInto(MASTERDATA_TYPE_A)
      .columns(MASTERDATA_TYPE_A.VERSION,
          MASTERDATA_TYPE_A.VERSION,
          MASTERDATA_TYPE_A.CODE, 
          // much more here
      )
      .select(DSL.select(
                  val(typeA.getVersion()),
                  val(typeA.getCode()),
                  // much more here
              )
              .whereExists(
                  context.select()
                      .from(MASTERDATA_VERSION)
                      .where(MASTERDATA_VERSION.VERSION.eq(typeA.getVersion()).and(MASTERDATA_VERSION.STATE.eq(MASTER_DATA_STATE_PROCESSING)))
              )
      )
      .returningResult()
      .fetch()
      .size() > 0;
}

It works fine and only insert data of version that are currently supposed to be inserted and skips older data if I reprocess all the data. However, I would like to write it in a more general way using a Record, because there are lots of other master data types. Something like:

public boolean writeRecord(TypeA typeA) {
  var newRecord = context.newRecord(MASTERDATA_TYPE_A, typeA);
  return context
      .insertInto(MASTERDATA_TYPE_A)
      .columns(newRecord.fields())
      .select(DSL.select(
                newRecord.valuesRow()
              )
              .whereExists(
                  context.select()
                      .from(MASTERDATA_VERSION)
                      .where(MASTERDATA_VERSION.VERSION.eq(typeA.getVersion()).and(MASTERDATA_VERSION.STATE.eq(MASTER_DATA_STATE_PROCESSING)))
              )
      )
      .returningResult()
      .fetch()
      .size() > 0;
}

Here valuesRow() returns just one Value and it does not match with the column list. Using the Record directly doesn't give any possibility to add a where clause.


Solution

  • Just call Fields::fields on that valuesRow():

    select(newRecord.valuesRow().fields())