tags:

views:

737

answers:

4

I have a many-to-one relationship where the child table can have hundreds of thousands of records. In this case, calling Parent.ChildCollection.Count forces a lazy initialization of the child collection which is extremely expensive.

In Hibernate 3.0 there is a feature lazy="extra" which allows you to check a subset of collection properties without lazy loading the whole thing.

Unfortunately this will not be available until NHibernate 2.1, which is still in Alpha. http://jira.nhibernate.org/browse/NH-855

How can I accomplish this with NHibernate 2.0.1?

I used to have special properties such as this

<property name="ChildCollectionCount" type="int" formula="(select count(*) from ChildTable child where child.parentID = parentID "/>

but I can't use these anymore because I am now sharing this library and its a performance problem for other users.

A: 

When you say its a performance problem for other users, do you mean they also want to access the collection, but its too large for them. Or is the code snippet/ChildCollectionCount too slow for them?

If its the first case, then perhaps you need to do a similar solution for them - identify exactly what they need and provide methods that offer that facility.

Chris Kimpton
A: 

Is the performance slow when using HQL or is that irrelevant to your problem?

Chris Kimpton
A: 

very late, but you can apply a filter on the collection

IQuery q = nhSession.CreateFilter(Parent.ChildCollection, "select count(*)");
long countResult = q.UniqueResult<long>();

this will not force an initialization of the collection but instead perform a single query to the db

Jaguar
A: 

I would recommend a seperate query, rather than a domain relationship. Then you can use all sorts of optimisations.

Noel Kennedy