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

我的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设置为null。因此,我的猜测是我的映射器未正确注册。

除了使用@RegisterMapper和@Mapper(SystemIdMapper.class)批注之外,我还尝试过:
dbi.registerMapper(new SystemIdMapper());

但仍然没有运气。

最佳答案

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

@GetGeneratedKeys(SystemIdMapper.class)

@Mapper或@RegisterMapper不用于获取ID。仅在从表中选择值时使用。

关于jdbi - 如何将JDBI @GetGeneratedKeys与Mapper结合,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32478300/

10-11 21:37