Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update only changed fields in JOOQ record using POJO

I'd like to update the changed fields in a JOOQ record using a POJO as the source. Record.from(Object) is nearly right, but according to the docs

The resulting record will have its internal "changed" flags set to true for all values.

I would like only the fields which have actually changed (as determined by say, Objects.equals(Object, Object)) to have their flags updated.

The two reasons for this are:

  • I don't want to trigger an insert
  • I only want to send new values to the database in the update statement (bandwidth, concurrent updates, etc)
like image 567
kag0 Avatar asked Jun 24 '16 00:06

kag0


1 Answers

The reason for this implementation ...

The resulting record will have its internal "changed" flags set to true for all values.

... is simple: If things weren't implemented this way, there would be no way to enforce an update of a value that hasn't changed. There are some use-cases where this is desireable (e.g. batching, avoiding too many different SQL strings, etc.). The Record.from() method is just consistent with the other Record methods, e.g. Record.set(Field, Object).

You can patch the internal changed flags as such:

// Load all values and mark them all as "changed"
record.from(object);

// Undo the undesired flags
for (int i = 0; i < record.size(); i++)
    if (Objects.equals(record.get(i), record.original(i)))
        record.changed(i, false);

I've also created a feature request in jOOQ. Perhaps the API could be improved as a lot of people have this requirement: https://github.com/jOOQ/jOOQ/issues/5394

like image 151
Lukas Eder Avatar answered Nov 18 '22 09:11

Lukas Eder