How to do in-query in jDBI?

Mohit Verma picture Mohit Verma · Oct 17, 2013 · Viewed 16.6k times · Source

How can I execute somethings like this in jDBI ?

@SqlQuery("select id from foo where name in <list of names here>")
List<Integer> getIds(@Bind("nameList") List<String> nameList);

Table: foo(id int,name varchar)

Similar to @SelectProvider from myBatis.

Similar questions has been asked How do I create a Dynamic Sql Query at runtime using JDBI's Sql Object API?, but somehow answer is not clear to me.

Answer

Deinlandel picture Deinlandel · Oct 23, 2013

This should work:

@SqlQuery("select id from foo where name in (<nameList>)")
List<Integer> getIds(@BindIn("nameList") List<String> nameList);

Don't forget to annotate class containing this method with:

@UseStringTemplate3StatementLocator

annotation (beacuse under the hood JDBI uses Apache StringTemplate to do such substitutions). Also note that with this annotation, you cannot use '<' character in your SQL queries without escaping (beacause it is a special symbol used by StringTemplate).