Jdbi - how to bind a list parameter in Java?

后端 未结 2 725
独厮守ぢ
独厮守ぢ 2020-12-10 03:00

We have an SQL statement which is executed by Jdbi (org.skife.jdbi.v2). For binding parameters we use Jdbi\'s bind method:

Handle h         


        
相关标签:
2条回答
  • 2020-12-10 03:33

    The article you linked also descibes the @BindIn annotation. This provides a general purpose implementiation for lists.

    @UseStringTemplate3StatementLocator
    public class MyQuery {
      @SqlQuery("select id from foo where name in (<nameList>)")
      List<Integer> getIds(@BindIn("nameList") List<String> nameList);
    }
    

    Please note that you'll have to escape all pointy brackets < like this \\<. There is a previous discusion on SO: How to do in-query in jDBI?

    0 讨论(0)
  • 2020-12-10 03:41

    I just wanted to add an example since I recently spent considerable time getting a slightly more complex scenario to work :

    Query :

    select * from sometable where id <:id and keys in (<keys>)
    

    What worked for me :

    @UseStringTemplate3StatementLocator
    public interface someDAO { 
    
        ....
        ....
        // This is the method that uses BindIn
        @Mapper(someClassMapper.class)
        @SqlQuery("select something from sometable where age \\< :age and name in (<names>)")
        List<someclass> someMethod (@Bind("age") long age, @BindIn("names") List<string> names);
    
        @Mapper(someClassMapper.class)
        @SqlQuery("select something from sometable where id = :id")
        List<someclass> someMethod1 (@Bind("id") long id);
        ...
        ...
    
    }
    

    Note: I did have to also add the below dependency since I am using

    @UseStringTemplate3StatementLocator 
    <dependency>
        <groupId>org.antlr</groupId>
        <artifactId>stringtemplate</artifactId>
        <version>3.2.1</version>
    </dependency>
    

    The main thing to observe in the above example : You only need to escape the less than operator (i.e. < ) and not the <> that surround the collection variable (names).

    As you can see I did not use a sql.stg file to write my queries in. Initially I incorrectly assumed that when using @UseStringTemplate3StatementLocator , we have to write the queries in the sql.stg file. However, somehow I never got my sql.stg file to work and I eventually reverted back to writing the query within the DAO class using @SqlQuery.

    0 讨论(0)
提交回复
热议问题