在 JDBI 中使用 IN 子句中的字符串列表
Use a list of strings in IN clause with JDBI
我正在为一个项目使用 JDBI/Dropwizard,并想 运行 一些简单的查询。我有这样的查询:
private static final String GET_STUFF = "SELECT * FROM myTable WHERE state IN (:desiredState)"
我像这样在我的方法中绑定变量:
@Mapper(MyType.class)
@SqlQuery(GET_STUFF)
public MyType getStuff(@Bind(desiredState) List<String> states);
但是,当 运行ning 时出现以下错误:
org.skife.jdbi.v2.exceptions.UnableToCreateStatementException:
Exception while binding 'desiredState'....
Caused by: org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.util.ArrayList. Use setObject() with an explicit Types value to specify the type to use.
我将 states
作为 String 类型的 ArrayList
传递,所以我对这里发生的事情有点困惑。有谁知道使用 JDBI In
的正确方法吗?
使用注释 @BindIn
而不是 @Bind
。
还有,:desiredState
应该写成<desiredState>
以下是对我有用的方法 (JDBI 3.1.1
):
import org.jdbi.v3.sqlobject.customizer.BindList;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
public interface JdbiRoom {
@SqlUpdate("update Room set available = 0 where id in (<roomIds>)")
int markRoomsAsUnavailable(@BindList("roomIds") List<Long> roomIds);
}
此外,我们发现 @BindIn
不能很好地与 @UseStringTemplateSqlLocator
注释一起使用,因此在使用命名查询时必须将 roomIds
作为查询参数传递(参见 https://github.com/jdbi/jdbi/issues/1131) 详情:
markRoomsAsUnavailable(roomIds) ::= <<
update rooms set available = 0 where id in (<roomIds>)
>>
@SqlQuery("SELECT ... WHERE xxx in (<uids>)")
@BindIn(value = "uids", onEmpty = BindIn.EmptyHandling.VOID) List<String> ids
不要忘记注释您的 class
@UseStringTemplate3StatementLocator
我正在为一个项目使用 JDBI/Dropwizard,并想 运行 一些简单的查询。我有这样的查询:
private static final String GET_STUFF = "SELECT * FROM myTable WHERE state IN (:desiredState)"
我像这样在我的方法中绑定变量:
@Mapper(MyType.class)
@SqlQuery(GET_STUFF)
public MyType getStuff(@Bind(desiredState) List<String> states);
但是,当 运行ning 时出现以下错误:
org.skife.jdbi.v2.exceptions.UnableToCreateStatementException:
Exception while binding 'desiredState'....
Caused by: org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of java.util.ArrayList. Use setObject() with an explicit Types value to specify the type to use.
我将 states
作为 String 类型的 ArrayList
传递,所以我对这里发生的事情有点困惑。有谁知道使用 JDBI In
的正确方法吗?
使用注释 @BindIn
而不是 @Bind
。
还有,:desiredState
应该写成<desiredState>
以下是对我有用的方法 (JDBI 3.1.1
):
import org.jdbi.v3.sqlobject.customizer.BindList;
import org.jdbi.v3.sqlobject.statement.SqlUpdate;
public interface JdbiRoom {
@SqlUpdate("update Room set available = 0 where id in (<roomIds>)")
int markRoomsAsUnavailable(@BindList("roomIds") List<Long> roomIds);
}
此外,我们发现 @BindIn
不能很好地与 @UseStringTemplateSqlLocator
注释一起使用,因此在使用命名查询时必须将 roomIds
作为查询参数传递(参见 https://github.com/jdbi/jdbi/issues/1131) 详情:
markRoomsAsUnavailable(roomIds) ::= <<
update rooms set available = 0 where id in (<roomIds>)
>>
@SqlQuery("SELECT ... WHERE xxx in (<uids>)")
@BindIn(value = "uids", onEmpty = BindIn.EmptyHandling.VOID) List<String> ids
不要忘记注释您的 class
@UseStringTemplate3StatementLocator