JPA 2 查询返回不完整的结果
以下查询仅匹配在 select 子查询中找到的第一个值,即使所有值都匹配 SELECT p FROM Profile p WHERE p.id IN (SELECT u.group FROM User u WHERE u.id = ? 1)
子查询返回一个逗号分隔的列表,如:1,2,3
。该查询应返回所有三个子查询选择结果的匹配项。有人知道可能出了什么问题吗?谢谢。
The following query is only matching the first value found in the select subquery, even though there are match for all values SELECT p FROM Profile p WHERE p.id IN (SELECT u.group FROM User u WHERE u.id = ?1)
The subquery returns a comma separated list like: 1,2,3
. The query should return matches for all three subquery select results. Anyone know what could be wrong? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
IN
子句在 JPQL 和 SQL 中都不能以这种方式工作。(..)
中的值不是“逗号分隔的字符串”,而是一个值列表。该列表可以按字面指定为逗号分隔的字符串,也可以通过子查询生成,就像您的情况一样。也就是说,查询中的条件为p.id IN ("1,2,3")
(而不是p.id IN (1,2,3)
),所以它不会产生期望的结果。因此,您不能使用强大的查询语言(JPQL 或 SQL)来针对非规范化模式编写查询(您的列包含值列表,因此它违反了 1NF)。如果
Profile
和User
之间存在多对多关系,请将其表示为带有中间连接表的多对多关系。IN
clause doesn't work this way neither in JPQL nor SQL.Value inside
(..)
is not a "comma separated string", it's a list of values. This list can be specified literally as a comma separated string, or it can be produced by subquery, as in your case. That is, condition in your query works asp.id IN ("1,2,3")
(rather thanp.id IN (1,2,3)
), so it doesn't produce the desired result.So, you can't use power of query languages (JPQL or SQL) to write queries against denormalized schema (your column contains a list of values, therefore it violates 1NF). If you have many-to-many relation between
Profile
s andUser
s, express it as many-to-many relation with intermediate join table.虽然
IN
运算符支持与子查询的结果进行比较,但您所做的事情不起作用(而且我很惊讶您竟然得到了一个结果)。在进一步讨论之前,让我引用一下 JPA 2.0 规范:因此,首先,
p.id
与子选择的返回类型不匹配(这实际上是一个“小”问题)。其次,这是一个主要问题和误解,您的查询不会导致类似这样的结果(使用“伪代码”):
这是您想要的 - 但其中
显然不是您想要的,并且不会”不工作。
我唯一的建议:规范化你的数据库。
While the
IN
operator supports comparison against the results of a subquery, what you're doing can't work (and I'm surprised that you even get one result). Before going further, let me quote the JPA 2.0 specification:So, first,
p.id
doesn't match the return type of the subselect (which is actually a "minor" issue).Second, and this is a major issue and misunderstanding, your query won't result in something like this (using "pseudo code"):
which is what you'd like - but in
which obviously is not what you want, and won't work.
My only advice: normarlize your database.