Skip to content
Advertisement

Returning id in generic insert using JOOQ

I have a very generic API to insert stuff using JOOQ to soem tables:

 void insert(@NonNull final Table<?> table,
                @NonNull final Collection<Field<?>> columns,
                @NonNull final Collection<Object> values) {
        dslContext.insertInto(table)
                .columns(columns)
                .values(values)
                .execute();
    }

Is there a way to return id of that inserted record? All primary keys of tables in my db are named “id” so I could ahrdcode it but I cannot find a way to return it and cast to Integer / Long. I’m using JOOQ 3.9.5.

EDIT: I use MSSQL underneath.

Advertisement

Answer

Write:

long insert(@NonNull final Table<?> table,
            @NonNull final Collection<Field<?>> columns,
            @NonNull final Collection<Object> values) {
    return dslContext
          .insertInto(table)
          .columns(columns)
          .values(values)
          .returningResult(table.field("ID")) // Replace with your field name case
          .fetchOne()
          .into(long.class);
}

This assumes you’re using generated code whose generated Table instances implement Table.getIdentity(). Alternatively, if you cannot provide an identity, you could write:

long insert(@NonNull final Table<?> table,
            @NonNull final Collection<Field<?>> columns,
            @NonNull final Collection<Object> values) {
    dslContext
          .insertInto(table)
          .columns(columns)
          .values(values)
          .execute();
    return dslContext.lastID().longValue();
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement