做一个“IN"使用 Hibernate 查询 [英] Doing an "IN" query with Hibernate
问题描述
我有一个字符串中的 ID 列表,并且想使用 Hibernate 来获取具有这些 ID 的行.TrackedItem
是一个 Hibernate/JPA 实体(对不起,如果我在这里混淆了命名).
I have a list of IDs in a String, and want to use Hibernate to get the rows with these IDs. TrackedItem
is a Hibernate/JPA entity (sorry if I'm getting the naming mixed up here).
我的代码是:
String idsText = "380, 382, 386";
ArrayList<Long> ids = new ArrayList<Long>();
for (String i : idsText.split(","))
{
ids.add(Long.getLong(i));
}
List<TrackedItem> items = TrackedItem.find("id IN (?)", ids).fetch();
但这失败了:发生JPAQueryException : Error while execution query from models.TrackedItem where id IN (?): java.util.ArrayList cannot be cast to java.lang.Long
如何使 IN
部分工作?谢谢.
How can I make the IN
part work? Thanks.
推荐答案
您的 JPQL 查询的语法不正确.要么使用(带有位置参数):
The syntax of your JPQL query is incorrect. Either use (with a positional parameter):
List<Long> ids = Arrays.asList(380L, 382L, 386L);
Query query = em.createQuery("FROM TrackedItem item WHERE item.id IN (?1)");
query.setParameterList(1, ids)
List<TrackedItem> items = query.getResultList();
或(带有命名参数):
List<Long> ids = Arrays.asList(380L, 382L, 386L);
Query query = em.createQuery("FROM TrackedItem item WHERE item.id IN :ids");
query.setParameterList("ids", ids)
List<TrackedItem> items = query.getResultList();
以下是 JPA 1.0 规范中有关参数的相关部分:
Below, the relevant sections of the JPA 1.0 specification about parameters:
以下规则适用于位置参数.
4.6.4.1 Positional Parameters
The following rules apply to positional parameters.
- 输入参数由问号 (?) 前缀后跟一个整数指定.例如:
?1
. - 输入参数从 1 开始编号.
注意,同一个参数可以在查询字符串中多次使用,并且查询字符串中参数的使用顺序不需要与位置参数的顺序一致.
命名参数是以:"符号为前缀的标识符.它遵循第 4.4.1 节中定义的标识符规则.命名参数区分大小写.
A named parameter is an identifier that is prefixed by the ":" symbol. It follows the rules for identifiers defined in Section 4.4.1. Named parameters are case sensitive.
示例:
SELECT c
FROM Customer c
WHERE c.status = :stat
3.6.1节描述了命名查询参数绑定的API
Section 3.6.1 describes the API for the binding of named query parameters
这篇关于做一个“IN"使用 Hibernate 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!