注册JDBI的可选项

时间:2015-07-13 23:40:23

标签: java jdbc guava dao jdbi

我收到No container builder available for com.google.common.base.Optional错误。

这是一个更全面的堆栈跟踪:

java.lang.IllegalStateException: No container builder available for com.google.common.base.Optional
    at     org.skife.jdbi.v2.ContainerFactoryRegistry.createBuilderFor(ContainerFactoryRegistry.java:75)
    at org.skife.jdbi.v2.Query.first(Query.java:271)
    at     org.skife.jdbi.v2.sqlobject.ResultReturnThing$SingleValueResultReturnThing.result(ResultReturnThing.java:112)
    at org.skife.jdbi.v2.sqlobject.ResultReturnThing.map(ResultReturnThing.java:48)
    at org.skife.jdbi.v2.sqlobject.QueryHandler.invoke(QueryHandler.java:45)
    at org.skife.jdbi.v2.sqlobject.SqlObject.invoke(SqlObject.java:175)
    at org.skife.jdbi.v2.sqlobject.SqlObject$1.intercept(SqlObject.java:75)
    at org.skife.jdbi.v2.sqlobject.CloseInternalDoNotUseThisClass$$EnhancerByCGLIB$$b270edb1.select(<generated>)

我有一个带有这样界面的DAO:

import com.google.common.base.Optional;

public interface MyDAO {
    @SqlQuery("something")
    Optional<Data> select();
}

这是我的数据访问层单元测试:

public class MyDAOTest {
    @Test
    public void shouldSelect() {
        DBI dbi = new DBI("jdbc:(something)", "something", "something");
        MyDAO myDAO = dbi.onDemand(MyDAO.class);
        Optional<Data> data = myDAO.select();
        assertFalse(data.absent());
    }
}

2 个答案:

答案 0 :(得分:8)

如果您使用的是com.google.common.base.Optional,请注册io.dropwizard.jdbi.OptionalContainerFactory并收到错误No container builder available for com.google.common.base.Optional

如果您使用的是java.util.Optional,请注册io.dropwizard.java8.jdbi.OptionalContainerFactory并收到错误No container builder available for java.util.Optional

我按照说明here

public class MyDAOTest {
@Test
public void shouldSelect() {
    DBI dbi = new DBI("jdbc:(something)", "something", "something");
    dbi.registerContainerFactory(new OptionalContainerFactory());
    ...
}

答案 1 :(得分:4)

确保您在测试代码中创建新的io.dropwizard.java8.jdbi.DBIFactory,而不是io.dropwizard.jdbi.DBIFactory。不幸的是,它们具有相同的名称,并且(根据我的经验)很容易在进口中遗漏。