tags:

views:

842

answers:

2

In our application, we have various objects set to lazy false based on the application needs. However, in one of the use case we want to ignore all the lazy settings within the HBM files, and get ONLY the target object.

So the question is: is there a way to specify in the HQL to fetch ONLY the target object irrespective of the HBM settings?

~Sri

+1  A: 

you can use setFetchMode on the Criteria before it is executed to override the HBM file setting

lomaxx
A: 

Sorry, not sure if you understood your question.

If you have to implement it for a specific class, you can just use SetFetchMode.

var query = session.CreateCriteria(typeof(MyClass));
query.SetFetchMode("PropertyA", FetchMode.Select);
query.SetFetchMode("PropertyB", FetchMode.Select);

Note: for many-to-one references the entity class itself must be mapped with lazy=true. If not, NHibernate doesn't even create a proxy class for it.


This is the answer if you want to lazy load the type in a generic, type-independent way:

You could find them with the metadata and add fetch modes to a criteria

I didn't try it, but I would start with the following code:

var meta = sessionfactory.GetClassMetaData(typeof(MyClass));

var query = session.CreateCriteria(typeof(MyClass));

for(int index = 0; index < meta.PropertyType.Length; index++)
{
  if (meta.PropertyType[index] == NHibernateUtil.Entity)
  {
    query.SetFetchMode(meta.PropertyNames[index], FetchMode.Select);
  }
}

This doesn't include collections. They are probably found with factory.GetCollectionMetadata(roleName), but you need to find out the roleName.

Stefan Steinegger