jOOQ insert/update from data class

1.3k Views Asked by At

jOOQ has this nice feature of letting you map results into a data class:

data class User(id: Int, email: String)

val users: List<User> = ctx.select().from(USERS).fetchInto(User::class.java)

Is there a similar way to write an insert using an automatic data mapping from a data class?

How about an update?

1

There are 1 best solutions below

2
On BEST ANSWER

The inverse of calling the various "into" methods, such as ResultQuery.fetchInto(Class) is to load data into a record using various "from" methods, e.g. Record.from(Object) or DSLContext.newRecord(Table, Object), so:

val user: User = ...
val record: UserRecord = ctx.newRecord(USERS, user);

// Using statements
ctx.insertInto(USERS).set(record).execute();
ctx.update(USERS).set(record).where(...).execute();

// Using UpdatableRecord. See Javadoc about each one of these:
record.insert();
record.update();
record.store();
record.merge();

Since your data class has no notion of "dirty flag", this will always set all the values in the UserRecord to Record.changed() == true. You can reset the changed flag if required.