2

When using NHibernate and lazy loading, how would I get this kind of behavior:

I have a Customer class, and the customer has many addresses (say 100 to make this make more sense).

I load my customer row, I want to just access 3 items from the addresses collection.

I don't want nHibernate to load all 100 addresses, but with lazy loading from what I understand, will load all of them?

I want 3 of them only, and I want to load all 3 at once, how would I get this behavior?

6 Answers 6

4

It depends on

  • if you need "just one" or a certain one
  • if you need the other items in the list later in the same session

You can use

  • filters to filter the collection. These filters are defined in the mapping file and activated and parameterized when using the session
  • AliasToEntityMap result transformer which lets you filter the collection within a query
  • batch fetching that fetches a certain amount of elements at once.
Sign up to request clarification or add additional context in comments.

Comments

2
<class name="Customer">
    <set name="Address" batch-size="3">
        ...
    </set>
</class>

Comments

1

I think Lazy Loading will not help you here. I would take this responsibility to the AddressDataProvider. You will get a collection of addresses based on the customer and other predicates (I think first address doesn't have any business value. One more thing first can vary. The order in which addresses are returned is arbitrary.)

- The last visited address.
- The closest address to the customer address.
- The latest (added) address

etc.

Address GetLastVisited(Customer c);
Address GetClosest(Customer c);

Just my 2 cents.

Comments

0

It's possible to add batch size, but making batch size to small you may end up having many database calls when iterating over them.

Comments

0

You could populate the collection using HQL or a Criteria which would only select 1 address, however then you won't be able to access the other addresses unless you reload the entity.

Worst case, you would need the Hibernate "with" keyword, which wasn't implemented in NHibernate.

Comments

0

Is there a Common Criteria for these records you want to see?. (For Eg: Something like the current Addresses?. (say Current addressFlag = 1 ?)

If that is the case, then you can use a Where Clause on the collection mapping.

eg:

<bag name="Addresses"  where="CurrentAddressFlag = 1" cascade="save-update" fetch="select" lazy="true">
      <key column="AddressId"/>
      <one-to-many class="Address"/>
</bag>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.