2

I'm trying to optimize my queries to DB. Currently we have mapping like this, but it may grow in a future. We are doing a lot of small operations to the object A, and most of them doesn't require to load all data. At the same time for showing data on UI we need to load all staff at once.

I was trying to add extra mapping, but looks like this is not a case here.

Here is mapping file:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" default-lazy="false">
    <class name="A" table="A" discriminator-value="?" dynamic-update="true" >

        <cache usage="nonstrict-read-write"/>

        <id name="AId" column="aId">
            <generator class="guid.comb" />
        </id>

        <bag name="B" table="B" inverse="true" outer-join="false" lazy="false" batch-size="50" >
            <cache usage="nonstrict-read-write"/>
            <key column="aId" />
            <one-to-many class="B" />
        </bag>

        <many-to-one name="C" column="cId" class="C" outer-join="true" not-found="ignore" />
        <many-to-one name="D" column="dId" class="D" outer-join="true" not-found="ignore" />

  </class>
</hibernate-mapping>

Is it possible to specify in ICriteria, that would retrieve just pain object A, or object A with any set internal objects B, C or D

Thanks.

1 Answers1

1

NHibernate does have solution for that. In fact, exactly these scenarios are expected by design of this ORM Tool. But first of all, please, try to stop using not lazy mapping.

Other words, we have to do it up-side-down. Keep the mapping lazy, and force querying to be ad hoc eager. To get some idea read:

Next steps. Change all your mapping to lazy="true" ... or skip it, because laziness is the default. Do not use default-lazy="false".

Having all mappings supporting laziness, we can override that behaviour in our queries. So in fact all these there A, B, C will be in this query selected with one SELECT sent to DB Engine:

var criteria = session.CreateCriteria<A>()
    .CreateAlias("B", "b")
    .CreateCriteria("C");

We can also specify type of the JOIN (inner, left). Also check NHibernate - CreateCriteria vs CreateAlias. And many more...

Here are some starting points, in the documentation (similar chapter 16 QueryOver):

Once playing with it more (and also with the one-to-many / collections) also check:

Community
  • 1
  • 1
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335