子类的HQL查询

时间:2010-06-09 09:12:29

标签: nhibernate hql

我的实体模型中定义了以下实体:

public class MyContainer
{
   public virtual ICollection<Base> Subs { get; set; }
}

public abstract class Base
{
   public virtual Guid Id { get; set; }
}
public abstract class Sub1 : Base
{
   public virtual int MyValue { get; set; }
}
public abstract class Sub2 : Base
{
   public virtual int MyValue { get; set; }
}

以及上述实体的以下FluentNHibernate映射:

public sealed class BaseMap : ClassMap<Base>
{
   public BaseMap()
   {
      Table("BaseTable");
      Id(e => e.Id);
   }
}

public sealed class Sub1Map : SubClassMap<Sub1>
{
   public Sub1Map()
   {
      Table("Sub1Table");
      KeyColumn("BaseId");

      Map(e => e.Myvalue);
   }
}

public sealed class Sub2Map : SubClassMap<Sub2>
{
   public Sub2Map()
   {
      Table("Sub2Table");
      KeyColumn("BaseId");

      Map(e => e.Myvalue);
   }
}

当我运行以下HQL时:

select sub
   from MyContainer container
        join fetch container.Subs sub
   where sub.MyValue = :p1

生成的SQL仅在其中一个子类的WHERE子句中应用约束,但是,生成的JOINS是正确的,即生成以下骨架SQL:

SELECT ...
FROM BaseTable bt
     INNER JOIN Sub1Table st1 ON ...
     INNER JOIN Sub2Table st2 ON ...
WHERE st1.MyValue = @p1

我希望在WHERE子句中有一个额外的OR:

SELECT ...
FROM BaseTable bt
     INNER JOIN Sub1Table st1 ON ...
     INNER JOIN Sub2Table st2 ON ...
WHERE st1.MyValue = @p1
      OR st2.MyValue = @p2

是否有我遗漏的东西,或者有没有办法重新编写HQL以便我可以引用WHERE子句中的每个子类并直接应用约束(假设它会生成附加约束)在生成的SQL中??

我正在使用NHibernate 3.0.0。

1 个答案:

答案 0 :(得分:1)

应该在Base中声明和映射MyValue。无法通过子类中定义的属性过滤基类,而无需转换为特定类:

where (b.class = Sub1 and b.MyValue = :p1) or (b.class = Sub2 and b.MyValue = :p1)

编辑: 或者在FNH1.2中可以使用union子类化:

public class BaseMap : ClassMap<Base>
{
    public BaseMap()
    {
        UseUnionSubclassForInheritanceMapping();
        Table("BaseTable");
        Id(e => e.Id);
    }
}