How to do in-query in jDBI?

后端 未结 4 608
轮回少年
轮回少年 2020-12-05 17:11

How can I execute somethings like this in jDBI ?

@SqlQuery(\"select id from foo where name in \")
List getIds(@Bind(         


        
4条回答
  •  失恋的感觉
    2020-12-05 18:05

    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 getIds(@BindStringList("nameList") List 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>() {
                    @Override
                    public void bind(SQLStatement q, BindStringList bind, Collection 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.

提交回复
热议问题