with jooq is there a generic way to 'select by id'?

Viewed 444

I'm pretty new to using jooq and I'm trying to implement the usual CRUD operations that us Java guys like to have in our DAOs/repositories. I have the following code for selecting a record by id:

public class JooqRepository<ID, E extends BaseObject<ID>, T extends Table<R>, R extends Record> {
...
  private final T table; // would be coming from constructor to concrete reference in the generated classes
...

  protected Optional<E> findById(ID id) {
    final TableField<R, ID> idField = (TableField<R, ID>) table.getIdentity().getField();
    return dsl.fetchOptional(table, idField.eq(id)).map(toEntity()); // conversion method omitted here
  }
...
}

My question is firstly would this approach work for all kinds of tables/records or only ones that use identity/auto-increment?

What if I use a DBMS that doesn't have this feature (e.g. Oracle)?

What if a table has a composite key?

And lastly: Is it even recommended to use jooq in that way or should we explicitly craft dedicated queries for every table?

1 Answers

While it is possible to use jOOQ as a Spring repository implementation, you could also just use jOOQ's out of the box DAO support, which works in a similar way. The main difference is that jOOQ DAOs are unopinionated auxiliary tools, that do not impose DDD as a modeling paradigm, they just simplify the most common CRUD operations on each of your tables.

You can subclass the generated DAOs in order to add more functionality, and inject them to your services like Spring's repositories.

Related