HQL syntax error : 'NHibernate.Hql.Ast.ANTLR.QuerySyntaxException'

HQL syntax error : 'NHibernate.Hql.Ast.ANTLR.QuerySyntaxException'

作为 HQL 的初学者,我有一个 SQL 查询,我正试图将其转换为 hql。

select * from (

   select *
   from CORRELATION_VUE
   where film = v_oldidfilm and FILM2 not in (
                           select c.idfilm
                           from cotes c
                           where idclient = v_idclient)
   order by CORRELATION desc
 
 )
 where rownum <= 3;

所以在 HQL 中我正在尝试这个:

ISession s = NHibernateHelper.GetCurrentSession();
ITransaction tx = s.BeginTransaction();
IQuery query = s.CreateQuery(
    @"select u from (
            select u from vueCorreliser u
                where u.film = :idfilm
                    and u.FILM2 not in (
                        select c.idfilm from cote c
                            where c.idclient = :idclient)
                order by u.CORRELATION desc)
        where rownum <= 3; ")
    .SetInt32("idfilm", idfilm)
    .SetInt32("idclient", idclient); 

IList<Film> result = query.List<Film>();
tx.Commit();
return result;

但我在 CreateQuery 行收到语法错误。

我做错了什么?

谢谢

虽然我认为这是 this other question from you 的重复,但这里有一个单独的、更明确的答案。

不支持 from 语句中的子查询。 (它在其他语句中支持它们,例如 where 条件。)您必须在 from.

中没有子查询的情况下重写查询

您的子查询似乎只是为了限制行数。从查询中删除行限制,并在 HQL 查询对象上使用 .SetMaxResults(yourMaxRowCount)

HQL中不需要终止语句;,不知道是否支持。我觉得不是,最好去掉。

var query = s.CreateQuery(
    @"select u from vueCorreliser u
        where u.film = :idfilm
            and u.FILM2 not in (
                select c.idfilm from cote c
                    where c.idclient = :idclient)
        order by u.CORRELATION desc")
    .SetInt32("idfilm", idfilm)
    .SetInt32("idclient", idclient)
    .SetMaxResults(4);

这应该可以修复 QuerySyntaxException

顺便说一下,您的交易使用模式不安全。使用本地范围的事务时,请始终将它们嵌套在 using 中以确保它们被正确关闭。

using (var tx = session.BeginTransaction())
{
    ...
    tx.Commit();
    return result;
}

即使在失败的情况下,事务也将始终被处理掉,这会导致它回滚(如果它仍在进行中)。