通过 JDBI dropwizard 使用自定义 where 条件

san*_*tel 2 java sql jdbi dropwizard

我正在尝试使用 dropwizard 探索 JDBI,我的客户代码如下。

public interface UserDao {
@SqlQuery("SELECT FROM `t_user` :cond")
@Mapper(UserMapper.class)
List<User> fetch(@Bind("cond") String cond);
}
Run Code Online (Sandbox Code Playgroud)

并尝试使用以下代码进行调用

Application.getJdbi().onDemand(UserDao.class).fetch("where logon_id="+p.getEmail()+"'");
Run Code Online (Sandbox Code Playgroud)

并得到以下问题

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM `t_user` 'where logon_id=sanjaypatel2525@gmail.com\''' at line 1
Run Code Online (Sandbox Code Playgroud)

我遇到了引号问题,因为它是作为字符串传递的。通过这种方式,我试图为所有查询实现通用的 where 子句代码。我的问题是 1. 如何解决这个问题。2. 这是这样的代码的正确方法吗?或者我们可以使用准备好的语句。如果是的话怎么办。

非常感谢提前:)

Man*_*dan 5

对于动态查询,使用 Define 而不是 Bind。

public interface UserDao {
 @SqlQuery("SELECT * FROM t_user :cond")
 @Mapper(UserMapper.class)
 List<User> fetch(@Define("cond") String cond);
}
Run Code Online (Sandbox Code Playgroud)

  • `@UseStringTemplate3StatementLocator 公共接口 UserDao { @SqlQuery("SELECT * FROM t_user &lt;cond&gt;") @Mapper(UserMapper.class) List&lt;User&gt; fetch(@Define("cond") String cond); }` (2认同)