如何结合 JDBI @GetGeneratedKeys 和 Mapper

how to combine JDBI @GetGeneratedKeys with Mapper

我希望 JDBI 将自动生成的主键(长整型值)转换为另一个 class。

我的 DAO:

@RegisterMapper(SystemIdMapper.class)
public interface SystemDao {
  @SqlUpdate("insert into systems(device_id, user_id) values(:deviceId.value, :userId.value)")
  @GetGeneratedKeys
  @Mapper(SystemIdMapper.class)
  SystemId insert(@BindBean("deviceId") DeviceId deviceId, @BindBean("userId") UserId userId);

}

我的映射器:

public class SystemIdMapper implements ResultSetMapper<SystemId> {
  @Override
  public SystemId map(int index, ResultSet r, StatementContext ctx) {
    return new SystemId(0L); //fake mapping to simplify example
  }
}

当我 运行 我的代码时,我在 FigureItOutResultSetMapper.map(..) 中得到了 NullPointerException 因为

f = factory.mapperFor(rt, ctx);

将 f 设置为空。所以我的猜测是我的映射器注册不正确。

除了使用@RegisterMapper 和@Mapper(SystemIdMapper.class) 注释我也尝试过:

dbi.registerMapper(new SystemIdMapper());

但仍然没有运气。

您需要在 GetGeneratedKeys 注释中指定映射器。

@GetGeneratedKeys(SystemIdMapper.class)

@Mapper 或@RegisterMapper 不用于取回 id。它仅在从 table.

中选择值时使用