6

jDBI 查询是否可以有可选(空)参数?我试图让可选参数在数据库查询中工作。我正在使用 dropwizard。

@SqlQuery("SELECT * \n" +
          "FROM posts \n" +
          "WHERE (:authorId IS NULL OR :authorId = author_id)")
public List<Post> findAll(@Bind("authorId") Optional<Long> authorId);

传递了 authorId 时查询有效,但当它为 NULL 时给我这个错误:

org.postgresql.util.PSQLException: ERROR: could not determine data type of parameter $1

这是我从中调用的资源路线:

@GET
public ArrayList<Post> getPosts(@QueryParam("authorId") Long authorId)
{
    return (ArrayList<Post>)postDao.findAll(Optional.fromNullable(authorId));
}

从我读过的内容来看,这是可能的,所以我猜我遗漏了一些东西或有一个明显的错误。任何帮助将不胜感激!

仅供参考 - 我也尝试过没有 guava Optional (由 dropwizard 支持) - 只是发送一个 authorId 作为一个空的 Long 。只要它不为空,这也有效。

4

1 回答 1

6

您需要DBIFactory在应用程序类上使用 java8 版本。它提供 java 8 可选支持以及 joda LocalDateTime。

Gradle 依赖项:(如果您使用的是 maven,请将其转换为 maven)

compile 'io.dropwizard.modules:dropwizard-java8-jdbi:0.7.1'

并确保您io.dropwizard.java8.jdbi.DBIFactory在 Applicaiton 类上导入并在运行时使用它。

public void run(T configuration, Environment environment) throws Exception {
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDatabase(), "database");
    ...
    ...
}
于 2014-11-25T12:27:03.303 回答