tags:

views:

300

answers:

6

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 1 item 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?

A: 

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.

Marek Tihkan
A: 

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.

jishi
A: 
<class name="Customer">
    <set name="Address" batch-size="3">
        ...
    </set>
</class>
zvolkov
+2  A: 

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.
Stefan Steinegger
A: 

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.

Petar Petrov
A: 

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>
Sree