Skip to content

Instantly share code, notes, and snippets.

@jakubkulhan
Last active January 20, 2016 19:35
Show Gist options
  • Save jakubkulhan/8ba8d3090d2f924828c4 to your computer and use it in GitHub Desktop.
Save jakubkulhan/8ba8d3090d2f924828c4 to your computer and use it in GitHub Desktop.
jOOQ (http://www.jooq.org/) + Java 8 Rulez! = type-safe queries, shared behavior using traits
public interface RepositoryTrait<TABLE extends TableImpl<RECORD>, RECORD extends Record, POJO> {
DSLContext db();
TABLE table();
}
public interface UpsertRepositoryTrait<TABLE extends TableImpl<RECORD>, RECORD extends Record, POJO> extends RepositoryTrait<TABLE, RECORD, POJO> {
default int upsert(List<POJO> items) {
if (items.size() < 1) {
return 0;
}
TABLE t = table();
RECORD record = t.newRecord();
record.from(items.get(0), t.fields());
InsertValuesStepN<RECORD> insert = db().insertInto(t).values(record.valuesRow().fields());
for (POJO item : items.subList(1, items.size())) {
record = t.newRecord();
record.from(item, t.fields());
insert = insert.values(record.valuesRow().fields());
}
return buildOnDuplicateKeyUpdate(insert.onDuplicateKeyUpdate()).execute();
}
InsertOnDuplicateSetMoreStep<RECORD> buildOnDuplicateKeyUpdate(InsertOnDuplicateSetStep<RECORD> step);
}
public class UserRepository implements UpsertRepositoryTrait<Users, UserRecord, User> {
@Autowired DSLContext db;
public DSLContext db() { return db; }
public Users table() { return Tables.USERS; }
public InsertOnDuplicateSetMoreStep<UserRecord> buildOnDuplicateKeyUpdate(InsertOnDuplicateSetStep<UserRecord> step) {
Users t = table();
return step
.set(t.FIRST_NAME, MySQLDSL.values(t.FIRST_NAME))
.set(t.LAST_NAME, MySQLDSL.values(t.LAST_NAME))
.set(t.EMAIL, MySQLDSL.values(t.EMAIL));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment