我知道有@GeneratedKeys,但我不能将它与处理程序一起使用(我在测试中使用了处理程序)。
是的,绝对可以使用句柄检索生成的键(例如,自动递增主键)(我假设您指的是handle而不是handler)。例如,假设生成一个整数密钥:
handle.createStatement("INSERT ...")
.bind("foo", foo)
.executeAndReturnGeneratedKeys(IntegerMapper.FIRST).first();
Run Code Online (Sandbox Code Playgroud)
请注意,存在对支持 的 JDBC 驱动程序的依赖性java.sql.Statement.getGeneratedKeys(),但如果注释驱动的返回方法适用于您的数据库,我希望这种方法也适用。
小智 5
在 JDBI 3 中,这已更改为
handle.createUpdate("INSERT ...")
.bind("foo", foo)
.executeAndReturnGeneratedKeys("id")
.mapTo(Long.class)
.one()
Run Code Online (Sandbox Code Playgroud)