views:

129

answers:

2

Dear ladies and sirs.

I have an object O with 2 fields - A and B. How can I fetch O from the database so that only the field A is fetched?

Of course, my real application has objects with many more fields, but two fields are enough to understand the principal.

I am using NHibernate 2.1.

Thanks.

EDIT:

I wish to clarify. I need to fetch objects of type O. Sometimes I will want to fetch complete objects - meaning both A and B fields are set from the database values. But on other occasions, I would like to fetch O objects with just the A field set from the database values.

A: 

HQL has a select new construct, which allows you to fetch only a subset of fields. Objects returned, however, cannot be saved back to the DB.

As an alternative, you can create additional classes with a limited set of properties an map those onto table in question.

Anton Gogolev
I need an ability to fetch partial objects of the same type as when fetching complete objects. Meaning instances of type O with just the field A initialized from DB.
mark
+2  A: 

Use a projection to narrow the result set to the desired column(s) and a result transformer to convert the result into the type that you want.

This will return transient objects rather than persistent entities.

// select some User objects with only the Username property set
var u = session.CreateCriteria<User>()
    .SetProjection( Projections.ProjectionList().Add(Projections.Property("Username"), "Username")  ) 
    .SetResultTransformer( Transformers.AliasToBean<User>() )
    .List<User>();
Lachlan Roche
Thanks for this Lachlan.Also wanted to add that you can use this to map to a different type as well. I took a User object with all the user's properties on it and used the transformer to generate a UserDto object which was drastically simplified with just the username for use when all I needed was a list of usernames for dropdown list.
Chris Stavropoulos