1

We use JOOQ code generation which works like a charm. For 99% of our use cases we simply reuse DAOs generated by JOOQ. For one usecase we need to use transactions.

I am looking at other questions such as the one here JOOQ & transactions and using JOOQ transactions to insert rows into two tables as a transaction. The tables are quite big with 15+ columns and I am thinking if there is a better way to do this other than

DSL.using(configuration)
   .transaction(ctx -> {
       DSL.using(ctx)
          .update(TABLE)
          .set(TABLE.COL, newValue)
          .where(...)
          .execute();
   });

Specifying the 15 columns seems like a lot of work which has to be redone when new columns etc are added. We already have POJOs is there any way to simply convert POJO into a record and simply using the DSL syntax.

Kannan Ekanath
  • 16,759
  • 22
  • 75
  • 101

1 Answers1

1

You can convert a POJO to a record like this:

ctx.dsl()
   .update(TABLE)
   .set(ctx.dsl().newRecord(TABLE, pojo))
   .where(...)
   .execute();

This will set all the columns in the table, which may be undesired (e.g. you may not want to set the primary key to itself). To prevent certain fields from being included, use Record.changed(Field, boolean), to reset the internal changed flag per column.

Alternatively, if your WHERE clause is just a predicate on the primary key, you can also just use UpdatableRecord.update():

ctx.dsl().newRecord(TABLE, pojo).update();
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • This is a very useful answer @Lukas! There should be a section in the JOOQ doc that explains how we can inter-operate between POJOs and Records. In general I think most developers want to work with POJOs and DAOs unless it is absolutely mandatory. – Kannan Ekanath Aug 04 '20 at 15:15
  • @KannanEkanath. *"There should be a section in the JOOQ doc that explains how we can inter-operate between POJOs and Records."* It's documented here: https://www.jooq.org/doc/latest/manual/sql-execution/fetching/pojos/, *"In general I think most developers want to work with POJOs and DAOs unless it is absolutely mandatory."* I don't think so. jOOQ's core feature is the DSL. You just happen to take a different approach, which is also supported by jOOQ. – Lukas Eder Aug 04 '20 at 15:29