使用JDBI v2和java.util.Optional“没有为java.util.Optional注册的映射器”

时间:2019-05-16 21:39:25

标签: java jdbi

当我尝试这样的代码时:

...
import java.util.Optional;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.customizers.RegisterMapper;
...

public abstract class SomethingDAO {
    @RegisterMapper(SomethingMapper.class)
    @SqlQuery("sql/something_select_by_id.sql")
    abstract Optional<Something> selectById(@Bind("id") long id);
}

为什么会产生这样的错误?

org.skife.jdbi.v2.MappingRegistry$1: No mapper registered for java.util.Optional

    at org.skife.jdbi.v2.MappingRegistry.mapperFor(MappingRegistry.java:83)
    at org.skife.jdbi.v2.RegisteredMapper.map(RegisteredMapper.java:35)
    at org.skife.jdbi.v2.Query$4.munge(Query.java:183)

2 个答案:

答案 0 :(得分:2)

您需要添加注释@SingleValueResult,如下所示:

public abstract class SomethingDAO {
    @RegisterMapper(SomethingMapper.class)
    @SqlQuery("sql/something_select_by_id.sql")
    @SingleValueResult
    abstract Optional<Something> selectById(@Bind("id") long id);
}

答案 1 :(得分:0)

使用“纯” JDBI(v2),您需要使用ContainerFactory配置DBI实例。
Here's the ContainerFactory for Optionals in dropwizard-jdbi
然后,您应该在创建DBI实例时添加它:

 dbi.registerContainerFactory(new OptionalContainerFactory());