Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Dynamic Sql Query at runtime using JDBI's Sql Object API?

Tags:

java

sql

mysql

jdbi

I've been moving an existing project from jdbc to jdbi, and I've been making much use out of jdbi's beautiful SQL Object API. We're using mysql.

While the SQL Object API can construct handled queries that are known at compile time, I couldn't find a way of generating queries at run time.

Specifically, I want to be able to do something like this:

@SqlUpdate(
  "UPDATE record SET "+
    @IfNotZero("foo") "foo=:foo" +
    @IfNotNull("bar") "bar=:bar" +
    @IfNotNull("baz") "baz=:baz" +
  "WHERE id=:id"
)
public abstract int updateRecord(
  @Bind("id") int id,
  @Bind("foo") int foo,
  @Bind("bar") String bar,
  @Bind("baz") String baz
);
like image 871
Hans Z Avatar asked Jan 13 '23 11:01

Hans Z


2 Answers

JDBI is not very well suited for constructing dynamic queries. IMO the whole point of this library is to separate code and SQL queries as much as possible.

However, your particular case might be solved by means of SQL:

COALESCE(:foo, foo) 

if 'foo' is the name of the column in the table, and :foo will resolve to NULL, then mysql SET will be effectively

SET foo=foo

i.e. it will do nothing (which is desired beaviour in your case). If :foo is not null, it will be equivalent to

SET foo=:foo
like image 179
Deinlandel Avatar answered Jan 27 '23 13:01

Deinlandel


See @Define annotation and UseStringTemplate3StatementLocator usage.

like image 32
Cemo Avatar answered Jan 27 '23 11:01

Cemo