Optional jDBI parameter
Is it possible to have optional (null) parameters with jDBI requests? I am trying to get additional parameters working in a database query. I am working with dropwizard.
@SqlQuery("SELECT * \n" +
"FROM posts \n" +
"WHERE (:authorId IS NULL OR :authorId = author_id)")
public List<Post> findAll(@Bind("authorId") Optional<Long> authorId);
The request works when authorId is passed, but gives me this error when it is NULL:
org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $1
This is the resource route I'm calling from:
@GET
public ArrayList<Post> getPosts(@QueryParam("authorId") Long authorId)
{
return (ArrayList<Post>)postDao.findAll(Optional.fromNullable(authorId));
}
From what I've read, this can be done, so I'm guessing I'm missing something or an obvious error. Any help would be greatly appreciated!
FYI. I also tried it without guava Optional (which is supported by dropwizard) - just sending authorId as Long which is null. This also works as long as it is not zero.
source to share
You need to use java8 version DBIFactory
for your application class. It provides additional support for java 8 as well as joda LocalDateTime.
Gradle dependency: (convert it to maven if you are using maven)
compile 'io.dropwizard.modules:dropwizard-java8-jdbi:0.7.1
and make sure you import io.dropwizard.java8.jdbi.DBIFactory
into Applicaiton class and use it in run mode.
public void run(T configuration, Environment environment) throws Exception {
final DBIFactory factory = new DBIFactory();
final DBI jdbi = factory.build(environment, configuration.getDatabase(), "database");
...
...
}
source to share