How to bind a list parameter in Java?

We have an SQL statement that is executed by Jdbi ( org.skife.jdbi.v2). For the binding parameters, we use the Jdbi method bind:

Handle handle = ...
Query<Map<String, Object>> sqlQuery = handle.createQuery(query);
sqlQuery.bind(...)

However, we have a problem with lists, and we are currently using for this String.format. Therefore, our request may look like this:

SELECT DISTINCT
    tableOne.columnOne,
    tableTwo.columnTwo,
    tableTwo.columnThree
FROM tableOne
JOIN tableTwo
    ON tableOne.columnOne = tableTwo.columnOne
WHERE tableTwo.columnTwo = :parameterOne
    AND tableTwo.columnThree IN (%s)

%sis replaced by String.format, so we need to create the correct line in java code. Then, after the replacement %s, we use the jdbi method bindto replace all other parameters ( :parameterOneor ?).

String.format jdbi? bind(String, Object), /. , , factory , , - .

+4
2

, @BindIn. .

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

, <, \\<. SO : jDBI?

+6

, :

:

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

:

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

}

. , ,

@UseStringTemplate3StatementLocator 
<dependency>
    <groupid>org.antlr</groupid>
    <artifactid>stringtemplate</artifactid>
    <version>3.2.1</version>
</dependency>

, : (.. <), < > , () .

, sql.stg . , @UseStringTemplate3StatementLocator sql.stg. - sql.stg , DAO @SqlQuery.

+5

Source: https://habr.com/ru/post/1606975/


All Articles