Search code examples
databasejdbi

is it possible to get the generated key from an insert using a handle in JDBI?


I know there is @GeneratedKeys, but I can't use it with a handler (I am using a handler in my tests).


Solution

  • Yes, absolutely it is possible to retrieve generated keys (e.g., auto-increment primary keys) using a handle (I'm assuming you mean handle rather than handler). For example, assuming an integer generated key:

    handle.createStatement("INSERT ...")
        .bind("foo", foo)
        .executeAndReturnGeneratedKeys(IntegerMapper.FIRST).first();
    

    Note that there is a dependency on the JDBC driver supporting java.sql.Statement.getGeneratedKeys(), but if the annotation-driven return approach works for your database I'd expect this approach will as well.