How to do in-query in jDBI?
Asked Answered
A

5

35

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.

Aborticide answered 17/10, 2013 at 10:45 Comment(1)
Did any of the answers solve this issue? im trying the @BindIn but no luck :(Eyesight
T
41

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).

Tallu answered 23/10, 2013 at 7:20 Comment(5)
How do I escape < inside the query?Gerome
Figured it out. You should do \\<Gerome
Need to add dependency as mention in https://mcmap.net/q/449947/-how-to-use-in-operator-with-jdbiBartholomeus
This works cool. But what if I want to apply lower function to each item in the list before doing the comparison. I tried lower(name) in (lower(<nameList>)). This of course doesn't work. Any idea?Minima
@VikasPrasad Why not pre-process arguments in the code before executing the query?Tallu
T
9

With PostgreSQL, I was able to use the ANY comparison and bind the collection to an array to achieve this.

public interface Foo {
    @SqlQuery("SELECT id FROM foo WHERE name = ANY (:nameList)")
    List<Integer> getIds(@BindStringList("nameList") List<String> nameList);
}

@BindingAnnotation(BindStringList.BindFactory.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.PARAMETER})
public @interface BindStringList {
    String value() default "it";

    class BindFactory implements BinderFactory {
        @Override
        public Binder build(Annotation annotation) {
            return new Binder<BindStringList, Collection<String>>() {
                @Override
                public void bind(SQLStatement<?> q, BindStringList bind, Collection<String> arg) {
                    try {
                        Array array = q.getContext().getConnection().createArrayOf("varchar", arg.toArray());
                        q.bindBySqlType(bind.value(), array, Types.ARRAY);
                    } catch (SQLException e) {
                        // handle error
                    }
                }
            };
        }
    }
}

NB: ANY is not part of the ANSI SQL standard, so this creates a hard dependency on PostgreSQL.

Thither answered 29/7, 2016 at 23:21 Comment(0)
W
8

Use @Define annotation to build dynamic queries in jDBI. Example:

@SqlUpdate("insert into <table> (id, name) values (:id, :name)")
public void insert(@Define("table") String table, @BindBean Something s);

@SqlQuery("select id, name from <table> where id = :id")
public Something findById(@Define("table") String table, @Bind("id") Long id);
Welkin answered 17/10, 2013 at 11:16 Comment(1)
I assume that you had to add @UseStringTemplate3StatementLocator to the class to support @Define, but how did you get it to still do argument binding (@Bind) in addition to @Define?Rotogravure
P
7

If you are using the JDBI 3 Fluent API, you can use bindList() with an attribute:

List<String> keys = new ArrayList<String>()
keys.add("user_name");
keys.add("street");

handle.createQuery("SELECT value FROM items WHERE kind in (<listOfKinds>)")
      .bindList("listOfKinds", keys)
      .mapTo(String.class)
      .list();

// Or, using the 'vararg' definition
handle.createQuery("SELECT value FROM items WHERE kind in (<varargListOfKinds>)")
      .bindList("varargListOfKinds", "user_name", "docs", "street", "library")
      .mapTo(String.class)
      .list();

Note how the query string uses <listOfKinds> instead of the usual :listOfKinds.

Documentation is here: http://jdbi.org/#_binding_arguments

Pepys answered 30/4, 2019 at 12:53 Comment(0)
F
0

Use @BindList annotation.

Example:

@SqlQuery("SELECT name FROM table WHERE id IN (<ids>)")
List<String> getNames(@BindList("ids") List<int> ids);
Fairweather answered 2/11, 2022 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.