Search code examples
javasqldropwizardjdbi

Use custom where condition with JDBI dropwizard


I am trying to explore JDBI with dropwizard, my custome code is as below.

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

and trying to call with below code

Application.getJdbi().onDemand(UserDao.class).fetch("where logon_id="+p.getEmail()+"'");

and getting below issue

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 [email protected]\''' at line 1

I am getting quotes issues as this is been passed as String. This way I am trying to achieve common where clause code for all the queries. My questions are 1. How to resolve this issue. 2. Is this is proper way to code like this, or we can use prepared statement. If yes then how.

Great Thanks in Advance :)


Solution

  • Use Define instead of Bind for dynamic queries.

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