HQL 中的 Linq“.any”等价物

Linq ".any" equivalent in HQL

我有一个 NHibernate Linq 查询,我需要将其转换为 HQL:

var result = Conexion.Session.Query<Person>();
result = result.Where(p => p.addresses.Any(a => a.City.Name == "mycity"));

Returns至少有一个地址在城市"MyCity"

的人

如何将 "any" 子句翻译成 "HQL sintax"?

谢谢。

这是 HQL 等价物:

select p 
from Person p
join p.addresses a
join a.city c
where c.name = :cityName

any简单的通过一对多连接where条件解决

如果同一个City中有多个地址,要去除Person实体重复项,需要使用distinct:

select distinct p 
from Person p
join p.addresses a
join a.city c
where c.name = :cityName

select distinct p 
from Address a 
join fetch a.person p 
join a.city c 
where c.name = :cityName

要复制由以下人员生成的 SQL:

var result = Conexion.Session.Query<Person>();
result = result.Where(p => p.addresses.Any(a => a.City.Name == "mycity"));

我们必须这样做:

var hql = "SELECT p FROM Person p WHERE EXISTS "
          + "(SELECT a FROM Address a "
          + "  LEFT JOIN a.City c "
          + "  WHERE p = a.Person " 
          + "    AND c.Name = 'mycity') ";

mycity 偶数参数:

var hql = "SELECT p FROM Person p WHERE EXISTS "
          + "(SELECT a FROM Address a "
          + "  LEFT JOIN a.City c "
          + "  WHERE p = a.Person " 
          + "    AND c.Name = :mycity) ";

var result = Conexion.Session.CreateQuery(hql)
        .SetParameter("mycity", "...")
        .List<Person()

万一 Address 有对 Person 的反向引用,那将起作用,因为那是条件 WHERE p = a.Person 的一部分

如果映射只包含从人到地址的路径,hql 必须是这样的:

var hql = "SELECT p FROM Person p WHERE EXISTS "
          + "(SELECT p2 FROM Person p2 "
          + "  LEFT JOIN p2.addresses a "
          + "  LEFT JOIN a.City c "
          + "  WHERE p = p2 " 
          + "    AND c.Name = :mycity) ";

即使从地址到人的引用丢失,这仍然有效