如何在jDBI中进行查询?
如何在jDBI中执行这样的事情?
@SqlQuery("select id from foo where name in ") List getIds(@Bind("nameList") List nameList);
表: foo(id int,name varchar)
与myBatis的@SelectProvider类似。
类似的问题已经被问到如何使用JDBI的Sql Object API在运行时创建动态Sql查询? ,但不知何故,答案对我来说并不清楚。
这应该工作:
@SqlQuery("select id from foo where name in ()") List getIds(@BindIn("nameList") List nameList);
不要忘记使用以下方法注释包含此方法的类:
@UseStringTemplate3StatementLocator
注释(因为引擎盖下JDBI使用Apache StringTemplate进行此类替换)。 另请注意,使用此批注时,不能在不进行转义的情况下在SQL查询中使用“<”字符(因为它是StringTemplate使用的特殊符号)。
使用@Define批注在jDBI中构建动态查询。 例:
@SqlUpdate("insert into (id, name) values (:id, :name)") public void insert(@Define("table") String table, @BindBean Something s); @SqlQuery("select id, name from
where id = :id") public Something findById(@Define("table") String table, @Bind("id") Long id);
使用PostgreSQL,我能够使用ANY比较并将集合绑定到数组来实现此目的。
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 } } }; } } }
注意:ANY不是ANSI SQL标准的一部分,因此这会对PostgreSQL产生硬依赖。
- 在Java中删除游戏中的对象(eclipse)
- 当我从solr查询时,它发生了一个常见的exception,告诉我未定义的字段userId
- DefaultTreeModel和Wicket Tree:setAsksAllowsChildren不起作用
- 列标题SWT中的控件(组合,单选,文本)
- 如何将JADE与任何其他前端接口?
- 是否可以在机器上运行可执行jar文件而不先安装java?
- java split()方法
- 使用MockMultipartHttpServletRequest进行unit testing(在ItemInputStream.makeAvailable中抛出NullPointerException)
- 即使没有内存,我会遇到java.lang.OutOfMemoryError吗?