Subquery using derived table in Hibernate HQL

拈花ヽ惹草 提交于 2019-12-06 03:58:32

问题


I have a Hibernate HQL question. I'd like to write a subquery as a derived table (for performance reasons). Is it possible to do that in HQL? Example:

FROM Customer WHERE country.id in 
(SELECT id FROM (SELECT id FROM Country where type='GREEN') derivedTable)

(btw, this is just a sample query so don't give advice on rewriting it, is just the derived table concept I'm interested in)


回答1:


Unfortunately no, derived tables don't currently work in HQL. For example, the following works:

List<int> result =
  nHSession.CreateQuery( @"select distinct Id from User u")
  .List<int>().ToList();

...the following throws the this exception: Exception of type 'Antlr.Runtime.NoViableAltException' was thrown. near line 1, column 24 [select distinct Id from (select u from S2.BP.Model.User u)]

List<int> result = nHSession.CreateQuery(
    @"select distinct Id from (select u from User u)")
    .List<int>().ToList();

The fall back would be to create a named query containing raw sql or to create a stored procedure and invoke it via named query, like so:

List<int> result = nHSession.GetNamedQuery("spUserIds")
    .SetInt32("id", 3)
    .List<int>().ToList();



回答2:


You can find some information about derived properties and performance considerations on my blog in http://blog.eyallupu.com/2009/07/hibernate-derived-properties.html

Hope it will help,
Eyal Lupu



来源:https://stackoverflow.com/questions/2433729/subquery-using-derived-table-in-hibernate-hql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!