Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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());
    }
}
like image 236
user4975679 Avatar asked May 09 '26 10:05

user4975679


2 Answers

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());
    ...
}
like image 114
user4975679 Avatar answered May 10 '26 23:05

user4975679


Make sure that you're creating a new io.dropwizard.java8.jdbi.DBIFactory, not io.dropwizard.jdbi.DBIFactory, in your test code. Unfortunately these have the same name and are (from my experience) easy to miss in the imports.

like image 28
swartzrock Avatar answered May 10 '26 23:05

swartzrock