Search code examples
javajdbcguavadaojdbi

Register Optional for JDBI


I got a No container builder available for com.google.common.base.Optional error.

Here is a fuller stack trace:

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

I have a DAO with an interface like this:

import com.google.common.base.Optional;

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

Here is my data access layer unit test:

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());
    }
}

Solution

  • Register io.dropwizard.jdbi.OptionalContainerFactory if you are using com.google.common.base.Optional and get the error No container builder available for com.google.common.base.Optional.

    Register io.dropwizard.java8.jdbi.OptionalContainerFactory if you are using java.util.Optional and get the error No container builder available for java.util.Optional.

    I followed the instructions here:

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