R – How to prevent NHibernate queries from returning subclasses

nhibernate

I'm using the NHibernate criteria API to load some entities from my database. My domain consists of an abstract class, Animal, which the concrete Cat class inherits from. Another concrete class, Tiger, inherits from Cat.

I need to load all Cats from the database, so I'm doing the following-

ICriteria criteria = session.CreateCriteria(typeof(Cat));
return criteria.List<Cat>();

What I'm finding is that both Cats and Tigers are returned by the query instead of just Cats. This makes sense, as a Tiger is a Cat. But in this particular case I only want Cats, and not the additional Tigers.

Does anyone know how I can achieve this?

Best Answer

This is actually a Feature. But i think you can do what you want by mixing "table per class hierarchy" with "table per subclass". Therefor you need a Discriminator Column on which you can perform the query on. This would look like the following:

<class name="Cat" table="Cat">
    <id name="Id" type="Int64" column="ID">
        <generator class="native"/>
    </id>
    <discriminator column="TYPE" type="string"/>

    <subclass name="Tiger" discriminator-value="TIGER">
        <join table="Tiger">
            <property name="..." column="..."/>
        </join>
    </subclass>
</class>

After this you should be able to query on the discriminator-column like this:

session.CreateCriteria<Cat>()
   .Add(Restrictions.IsNull("TYPE"))
   .List<Cat>();
Related Topic