NHibernate: query criteria for an object and possibly a subclass in the same query

This is the setting for my two objects:

public class Person {
  public Guid Id {get;set;}
  public string Name {get;set;}
}

public class Immortal : Person {
  public string DarkName {get;set;}
}

Here's what their displays look like:

<class name="Person">
  <id name="Id">
    <generator class="guid.comb"/>
  </id>
  <property name="Name" />

  <joined-subclass name="Immortal">
    <key column='PersonId' />
    <property name="DarkName" />
  </joined-subclass>
</class>

So that setting, 2 objects, one is a combined subclass of the other. I have a search structure that takes any number of criteria from a form and then applies the appropriate criteria to the query and then returns the results.

Now say that I have one form field in this case, “Name” - I want to return all people, whether they are normal Persons or this special class of creatures Immortal, seeing if their name matches the Name Person property, but in the case of the Immortal , I would also like to consider it a coincidence if their DarkName matches what was given in the form.

, , ? , NHibernate ICriteria, - Immortal, , , root Person . 10 (30 +) .

HQL, , , Immortal , HQL - , . , , :

select person from Person person
  outer join Immortal immortal on immortal.PersonId = person.Id
  where
    person.Name = :name or
    immortal.DarkName = :name

stackoverflow?

+3
1

SQL, .

laxness .

var list = session.CreateCriteria<Person>()
    .Add( Expression.Disjunction()
        .Add( Expression.Eq( "Name", name ) )
        .Add( Expression.Eq( "ImmortalName", name ) )
        )
    .List<Person>();

SQL:

SELECT this_.Id             as Id0_0_,
       this_.Name           as Name0_0_,
       this_1_.ImmortalName as Immortal2_1_0_,
       case 
         when this_1_.Id is not null then 1
         when this_.Id is not null then 0
       end as clazz_0_
FROM   person this_
       left outer join immortal this_1_
         on this_.Id = this_1_.Id
WHERE  (this_.Name = 'foo' /* @p0 */
         or this_1_.ImmortalName = 'foo' /* @p1 */)

:

<class name="Person" table="person">
    <id name="Id">
        <generator class="identity" />
    </id>
    <property name="Name" />
    <joined-subclass name="Immortal" table="immortal">
        <key column="Id" />
        <property name="ImmortalName" />
    </joined-subclass>
</class>
+3

Source: https://habr.com/ru/post/1733097/


All Articles