2015-09-09 48 views
3

我想讓JDBI將自動生成的主鍵(Long值)轉換爲另一個類。如何將JDBI @GetGeneratedKeys與Mapper結合使用

吾道:

@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); 

set f爲null。所以我的猜測是我的映射器被錯誤地註冊了。

除了使用@RegisterMapper和@Mapper(SystemIdMapper.class)註解我也試過的:

dbi.registerMapper(new SystemIdMapper()); 

,但仍沒有運氣。

回答

3

您需要在GetGeneratedKeys註釋中指定映射器。

@GetGeneratedKeys(SystemIdMapper.class) 

@Mapper或@RegisterMapper不用於獲取id返回。它僅在從表格中選擇值時使用。