做一个“IN”用Hibernate查询 [英] Doing an "IN" query with Hibernate

查看:100
本文介绍了做一个“IN”用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).

我的代码是:

My code is:

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:执行查询时出错from models.TrackedItem其中id IN(?):java.util.ArrayList不能转换为java.lang.Long

使 IN 部分工作?谢谢。

推荐答案

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();

或(使用命名参数):

Or (with a named parameter):

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位置参数



以下规则适用于位置参数

4.6.4.1 Positional Parameters

The following rules apply to positional parameters.


  • 输入参数由问号(?)前缀后跟一个整数指定。例如:?1

  • 输入参数从1开始编号。相同的参数可以在查询字符串中多次使用,并且查询字符串中参数的使用顺序不需要与位置参数的顺序一致。

  • Input parameters are designated by the question mark (?) prefix followed by an integer. For example: ?1.
  • Input parameters are numbered starting from 1.
    Note that the same parameter can be used more than once in the query string and that the ordering of the use of parameters within the query string need not conform to the order of the positional parameters.

命名参数是以:符号为前缀的标识符。它遵循第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.

示例:

Example:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆