Helper class to handle inserting content from messages into a table.
The helper will only select values form the message itself, not using
nested structure or anything like that.
The inserter is built in such a way that you can create the inserter
(even as a static field), and use it any number of times with a handle
to do the pre-programmed insert. The execute method is thread safe, as
long as none of the modification methods are called.
class MyInserter {
private static final MessageUpserter<MyMessage,MyMessage._Field> INSERTER =
new MessageUpserter.Builder<>("my_message")
.set(MyMessage.UUID, MyMessage.NAME)
.set("amount", MyMessage.VALUE, Types.INTEGER) // DOUBLE -> INTEGER
.onDuplicateKeyUpdate(MyMessage.VALUE)
.build();
private final Jdbi dbi;
public MyInserter(Jdbi dbi) {
this.dbi = dbi;
}
int insert(HandleMyMessage... messages) {
try (Handle handle = dbi.open()) {
return INSERTER.execute(handle, messages);
}
}
}
Or it can be handled in line where needed. The building process is pretty cheap,
so this should not be a problem unless it is called
a lot for very small
message.
class MyInserter {
int insert(HandleMyMessage... messages) {
try (Handle handle = dbi.open()) {
return new MessageUpserter.Builder<MyMessage,MyMessage._Field>("my_message")
.set(MyMessage.UUID, MyMessage.NAME)
.set("amount", MyMessage.VALUE, Types.INTEGER) // DOUBLE -> INTEGER
.onDuplicateKeyUpdateAllExcept(MyMessage.UUID)
.build()
.execute(handle, messages);
}
}
}
The rules for using this is pretty simple:
-
All fields set must be specified before onDuplicateKey* behavior.
-
Only one of
onDuplicateKeyIgnore and onDuplicateKeyUpdate
can be set.
-
execute(...) can be called any number of times, and is thread safe.