为什么直接在HQL中直接使用列名有时只能起作用? [英] Why does using a column name directly in HQL only work sometimes?
问题描述
我有两个HQL查询,我正在使用它们进行快速和肮脏的单元测试.第一个看起来像这样:
I have two HQL queries I am using for a quick-and-dirty unit test. The first looks somewhat like this:
from Foo where SOME_FOREIGN_KEY = 42
第二个看起来像这样:
from Foo as foo
inner join foo.Bar as bar
where foo.SOME_FOREIGN_KEY = 42
SOME_FOREIGN_KEY列不是Hibernate知道的映射名称.
The SOME_FOREIGN_KEY column is not the name of something that Hibernate knows is mapped.
由于某种原因,第一个HQL查询有效,但第二个HQL查询无效.
For some reason, the first HQL query works, but the second one does not.
我的目标是使第二个版本能够正常工作,而无需将对象图遍历到由外键标识的对象.对于此测试,我有一个已知的ID,并且只希望与该ID相关的对象.关系另一端的对象本身是无关紧要的.这可能吗?
My goal here is to get the second version to work, without traversing the object graph to the object identified by the foreign key. For this test, I have a known ID and I only want the objects related to that ID. The object itself on the other end of the relationship is irrelevant. Is this possible?
推荐答案
由于某种原因,第一个HQL查询有效,但第二个HQL查询无效.
For some reason, the first HQL query works, but the second one does not.
当您在HQL查询的WHERE
子句中使用Hibernate未知的内容(例如,未在SQL方言中注册的函数)时,Hibernate会表现得很聪明,并且会将其直接传递给数据库.
When you use something that isn't known by Hibernate in the WHERE
clause of an HQL query (e.g. a function that is not registered in the SQL dialect), Hibernate acts smartly and passes it directly to the database.
换句话说,假设Foo
映射到TABLE_FOO
,则以下HQL
In other words, assuming Foo
is mapped on TABLE_FOO
, the following HQL
from Foo where SOME_FOREIGN_KEY = 42
转换为以下SQL
SELECT FROM TABLE_FOO WHERE SOME_FOREIGN_KEY = 42
,并且如果TABLE_FOO
实际上具有SOME_FOREIGN_KEY
列,则可以使用.
And works if TABLE_FOO
actually has a SOME_FOREIGN_KEY
column.
但是,当使用第二个示例中的别名时:
However, when using an alias like in the second example:
from Foo as foo where foo.SOME_FOREIGN_KEY = 42
Hibernate尝试将SOME_FOREIGN_KEY
解析为Foo
实体的属性,但这显然失败了.
Hibernate tries to resolve SOME_FOREIGN_KEY
as a property of the Foo
entity, and this obviously fails.
我的目标是使第二个版本能够正常工作,而无需将对象图遍历到由外键标识的对象.
My goal here is to get the second version to work, without traversing the object graph to the object identified by the foreign key.
如果您为该列添加别名,则不会.因此,以下方法应该起作用:
It won't if you prefix the column with the alias. So the following should work:
from Foo as foo
inner join foo.Bar as bar
where SOME_FOREIGN_KEY = 42
但是,老实说,我不明白为什么您不想使用路径表达式,我建议您不要使用上述解决方案. HQL的目的之一是抽象表和列名,您将在此完全击败这个目标.
But honestly, I don't understand why you don't want to use a path expression and I would advice against using the above solution. One of the the point of HQL is to abstract the table and column names and you would be totally defeating this goal here.
这篇关于为什么直接在HQL中直接使用列名有时只能起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!